Matlab Intro Marsh

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Introduction to MATLAB

Eric Marsh
Penn State University
Aug 17, 2001

MATLAB efficiently manipulates matrices of different dimensions (m × n), and can also handle
scalars and vectors by treating them as 1 × 1 and 1 × n (or n × 1) matrices. The ability of
MATLAB to organize data into matrix form allows the user to perform theoretical and numerical
system analyses within a friendly environment.

General Information about MATLAB


§ The double greater than sign (») is the MATLAB prompt.

§ MATLAB is case-sensitive: The variable called A cannot be referred to as a.

§ Using the arrow keys can save you typing! The up ­ and down ¯ arrow keys allow for
scrolling through previously typed commands and the left ¬ and right ® arrow keys will
allow for editing the current command at the prompt.

§ There are five permanent variables: i = j = sqrt(-1), pi = 3.1415, NaN =


0/0, Inf = 1/0.

§ Semicolons after statements prevent listing of the variable content.

§ The clear command will clear the session by deleting all variables. To clear the screen type
clc at the MATLAB prompt, and to clear the graphics window use clf.

§ To exit MATLAB type exit at the prompt.

Obtaining Help
You can get help by typing help at the prompt or by clicking the mouse button on the Help
heading located in the command bar across the top of the screen. Once in the help window, you can
search for a specific term.

The function lookfor search-term displays a list of the possible MATLAB functions that
contain the string search-term in the help section of the listed functions. Then, typing in
help function will display the help section of that particular function or command as well as
specific syntax and options for it.

The next example shows how to use these two very important functions to look for the function
that calculates the cosine of a number.

MATLAB - Command Window


» lookfor cosine
ACOS Inverse cosine.
ACOSH Inverse hyperbolic cosine.
COS Cosine.
COSH Hyperbolic cosine.
TFFUNC time and frequency domain versions of a cosine modulated Gaussian pulse.
CHIRP Swept-frequency cosine generator.
DCT Discrete cosine transform.
dctold.m: %DCT Discrete cosine transform.
FIRRCOS Raised Cosine FIR Filter design.
IDCT Inverse discrete cosine transform.
idctold.m: %IDCT Inverse discrete cosine transform.
» help cos
COS Cosine.
COS(X) is the cosine of the elements of X.

Methods of Inputting Data


A single variable is the simplest input in MATLAB and only requires typing at the prompt the
variable's name, an equal sign, and its value (just like regular computer programming). The value can
be real, complex, or a function of other variables.

MATLAB - Command Window


»x = 2.7183
x =
2.7183

»y = pi
y =
3.1416

»theta = x + y*i
theta =
2.7183 + 3.1416i

Remember that although the variable theta is a scalar element, MATLAB still treats it as a 1 × 1
matrix. To create larger matrices there are three important rules:

§ Brackets [ ] surround matrices.

§ Commas or blank spaces separate matrix elements or columns.

§ Semicolons separate rows.

MATLAB - Command Window


»M = [11 12 13; 21 22 23; 31 32 33]
M =
11 12 13
21 22 23
31 32 33

Parts of matrices including single elements, rows, or columns may be assigned to another variable to
perform further operations, just as in programming languages like Fortran and C. Assigning the
element from the 3rd row and 2nd column of the M matrix to the variable m32 is done by:

MATLAB - Command Window


»m32 = M(3,2)
m32 =
32

2
Assigning the entire 3rd row of the M matrix to the row vector m_3 is done by:

MATLAB - Command Window


»m_3 = M(3,:)
m_3 =
31 32 33

Assigning the 2nd column of the M matrix to the column vector m_2 is done by:

MATLAB - Command Window


»m_2 = M(:,2)
m_2 =
12
22
32

Another useful method for inputting data into a 1 × n row vector is an array. An array is just a
series of numbers. Use a colon to separate the starting number, the step size, and the last number of
the array. The default step size is 1.

MATLAB - Command Window


»t = [1: 5]
t =
1 2 3 4 5

»t = [2: -0.5: 0]
t =
2.0000 1.5000 1.0000 0.5000 0

Remember that placing a semicolon ; after the input prevents MATLAB from echoing the input.
MATLAB stores the variable in memory but does not print it in the command window. The
function is useful when dealing with large matrices.

Arithmetic Functions
The following examples assume the declaration of the matrix A as follows:

MATLAB - Command Window


»A = [1 2; 3 4]
A =
1 2
3 4

Multiplication of the matrix A by a scalar:

MATLAB - Command Window


»B = A*2
B =
2 4
6 8

Addition of A to B (both matrices must be the same dimension):

3
MATLAB - Command Window
»C = A + B
C =
3 6
9 12

Multiplication of A by A (the dimensions must follow the multiplication rules for matrices):

MATLAB - Command Window


»D = A * A
D =
7 10
15 22

Element-wise multiplication of the A by A:

MATLAB - Command Window


»E = A .* A
E =
1 4
9 16

Transposing a matrix A:

MATLAB - Command Window


»F = A'
F =
1 3
2 4

Finding roots of a polynomial y = x2 - 5x + 6. At the MATLAB prompt, use the function roots
with an argument equal to the row vector containing the numerical coefficients of the polynomial in
descending order of power x:

MATLAB - Command Window


»R = roots([1 -5 6])
R =
3
2

Finding a polynomial from its roots {x = 1, 4, 8}. Use the function poly with an argument equal
the row vector containing the roots of the polynomial. The corresponding polynomial is y = x3 -
13x2 + 44x - 32.

MATLAB - Command Window


»P = poly([1 8 4])
P =
1 -13 44 -32

Other MATLAB Mathematical Functions


Absolute value abs(-5) = 5, abs(3 + 4i) = 5

4
Square root sqrt(4) = 2

Complex conjugate conj(5 + 2i) = 5 - 2i

Exponential (e) exp(1) = 2.7183

Natural log log(2) = 0.6931

Phase angle (in radians) angle(5 + 2i) = 0.3805

Sine/arcsine function sin(pi/2) = 1, asin(1) = 1.5708

Cosine/arccosine function cos(pi) = -1, acos(1) = 0

Tangent/ arctangent tan(pi/4) = 1, atan(1) = 0.7854

Setting the Working Directory in MATLAB


The working directory of your MATLAB session is changed using the cd command (especially if
you are saving your m-files on a floppy disk). The only directory that you will be able to save your
data on is c:\temp. All other directories on this computer are write-protected. Please note that the
c:\temp directory can and will be erased at arbitrary times throughout the semester so save your
data on a floppy disk before leaving the lab!

Saving MATLAB Variables: save and load


The save function will save the specified variables to a file with a .mat file extension that can
later be loaded using the load function.

Going back to our previous examples, let us save the last two variables R and P to a file called
rootpoly.

MATLAB - Command Window


»cd c:\temp
»save rootpoly R P

As you guessed, the first argument of the save function should be the name of the file (the
extension .mat is understood) where all the variables will be saved. As the example above shows,
you can add as many variables as you want just by separating them with spaces. The command
save fname (without including any variables) will save all the existing variables to the file
fname.mat. You can retrieve the variables R and P as follows using the load function.

MATLAB - Command Window


»load rootpoly

The function diary also allows you to save your data displayed on the screen to a text-file.
Basically, what this function does is to act like a recorder by making a copy of anything you type or
display in the command window, in other words: You get what you see in the command window!
Take a careful look at the example below to see how this function works.

MATLAB - Command Window


»x = [1:1:5]';
»y = x.^2;

5
»diary square.txt
»[x y]
ans =
1 1
2 4
3 9
4 16
5 25
»diary off
»%This line will not be written to the text-file square.txt

A text-file called square.txt was created containing the output (the exclamation point lets you
enter in DOS commands at the MATLAB prompt).

MATLAB - Command Window


»!type square.txt
[x y]
ans =
1 1
2 4
3 9
4 16
5 25
diary off

Note that we did not place the semicolon at the end of the previous commands because we want the
output to be displayed in the command window and recorded into the file square.txt. Also
note that the only text that was recorded to the file square.txt was the text displayed between
the diary square.txt and diary off instructions. For more information about these two
commands use the help function.

Basic Graphing in MATLAB


MATLAB can plot data against its own indices (location within the matrix) or against another set of
data as long as the dimensions of the matrices have the proper size. Listed below you can find some
examples showing the basic steps to plot your data. At the end of this topic, there is a list of most
functions and commands frequently used to change the different properties of a graph.

We will start by making up some data to try plotting.

MATLAB - Command Window


»t=[0:.015:10]';
»DataA = (-t+10).*cos(6*t);

Remember, a quotation mark ' after a matrix or array will give you its transpose. Note that you
must first define the variable t before you can use it as input for the equation defining DataA.

Use the function plot to graph DataA as a function of t.

MATLAB - Command Window


»plot(t, DataA)

6
10

−2

−4

−6

−8

−10
0 1 2 3 4 5 6 7 8 9 10

At this point, a graph should appear similar to the figure shown above. To superimpose another set
of data (DataE) onto this graph, use the hold command. First, you must click on the figure that
contains the graph (Figure No. 1). This action will make the axes of that figure current, in case you
have other figures open. Then, use the command hold on to freeze a plot so that you can add
more lines. If you do not use the hold command, MATLAB will erase the present graph and will
plot only the last set of data that was passed to the plot function. Plot a new variable DataE on
top of the existing graph of DataA by typing:

MATLAB - Command Window


»DataE = (-t+10).*cos(6*t + 1.5) + 1.2;
»hold on
»plot(t, DataE)

15
DataA
DataE

10

−5

−10
0 1 2 3 4 5 6 7 8 9 10

You can also access most of the important editable features of a graph by the Tools pop-up menu
in the graphics window. For titles, labels, grid, etc., right-click on the background of the graph and
also click properties. As a final step, add a legend by right clicking in the axes area and then click on
the show legend option of the pop-out menu. Drag the legend to the desired position and edit its
content by double clicking on the specific name of the data.

Overlaying Data and the Subplot Function


MATLAB also allows plotting multiple lines without having to use the hold command. To plot t
vs. DataA and t vs. DataE on the same graph:

7
MATLAB - Command Window
»plot(t, DataA, t, DataE)

15
DataA
DataE

10

−5

−10
0 1 2 3 4 5 6 7 8 9 10

It is also possible to plot two or more graphs on one screen without overlaying them. The function
subplot(x,y,n) will divide the graphics screen into a grid for separate plots. Here:

§ x is the number of rows


§ y is the number columns
§ n is the desired location of the graph being plotted.

Here is an example of the subplot function.

MATLAB - Command Window


»hold off
»subplot(2,1,1), plot(t, DataA)
»subplot(2,1,2), plot(t, DataE)

10

−5

−10
0 1 2 3 4 5 6 7 8 9 10

15

10

−5

−10
0 1 2 3 4 5 6 7 8 9 10

To add grids, titles, labels, and legends just follow the instructions stated in the prior subtopic.

Changing Line-type, Marker, and Color


For vectors or matrices x and y (e.g., x = [0: 0.01: 10]; y = sin(x)):

To change the line-type:

8
Solid line (default) plot(x, y, '-')
Dashed line plot(x, y, '--')
Dotted line plot(x, y, ':')
Dot-dash line plot(x, y, '-.')
To change the marker:

Dots plot(x, y, '.')


Stars plot(x, y, '*')
x's plot(x, y, 'x')
Circles plot(x, y, 'o')
+ symbols plot(x, y, '+')
To change the line color:

yellow line (default) plot(x, y, 'y')


red plot(x, y, 'r')
green plot(x, y, 'g')
white plot(x, y, 'w')
blue plot(x, y, 'b')
Grid, title, labels, and legend:

Grid on or off grid on, grid off


Add a title title('Text between quotes')
X-axis label xlabel('Text between quotes')
Y-axis label ylabel('Text between quotes')
Add a legend legend('legend 1','legend 2', …)
Plot limits axis([xmin xmax ymin ymax])

For the following example we plot a blue dotted line with red X markers on top:

MATLAB - Command Window


»plot(x, y, 'b:x')

Any combination of color and line-type or color and data point type can be obtained by replacing
the desired color and type in the above plot statement. MATLAB also has the ability to do many
other types of plots including: bode, logspace, semilogx, semilogy, margin, nichols,
and nyquist diagrams. Try help plot at the MATLAB prompt for more information.

Inserting MATLAB's graphs in Another Document


Once you have made some nice graphs of your data you might want to include them in the main
document of your lab report, right? To accomplish this just cut and paste:

§ Go to the figure that contains the graph you want to insert in the other document and click
Edit\Copy Figure to place the graph in the clipboard.

9
§ Go to (or open) the document where you want to insert the graph and place the cursor
where you want the graph to appear. Click Edit\Paste (Ctrl+V will also do the trick) and
then resize the image to your satisfaction.

You will get nicer looking results if you print your plot windows to a jpeg graphics file that you can
later insert into Word.

MATLAB - Command Window


»plot([1:.1:20], sin([1:.1:20]))
»print prettypicture -djpeg80

This will make a high resolution jpeg file called prettypicture.jpg of your current MATLAB
graphic window. Remember that you must be in the c:\temp directory to write data to the disk.

Creating M-Files and functions


It is often easier to create an m-file containing a sequence of instructions instead of typing them into
the MATLAB prompt one at a time. To do this, follow these three steps:

§ Type cd c:\temp to change the working directory to the temp directory. Remember
that only the temp directory is writable on the Vibes Lab computers.

§ Create a new m-file filename.m and type all the commands you would type normally at
the MATLAB prompt using the built-in text editor/debugger.

§ Save this text-file in the same directory where MATLAB is working (the cd command will
show the current working directory - it should be c:\temp) and make sure that the
extension of the file is .m. If you make a mistake you can simply go to the text-file, correct
the error, and save the text-file again instead of typing all the instructions again.

§ To execute the m-file type in its filename (without the extension .m) at the MATLAB
prompt.

If you wish to include comments in your file, start those lines with a %. If a line of code is too long
you can split it up by placing three dots … where you wish to cut the line. The m-file to plot the
prior graph will look like this:

MATLAB - filename.m
%Anakin Skywalker
%ME 85, 1/1/2001
%It is strongly recommended that you always include comments at
%the top of your MATLAB scripts describing what it does and any
%other relevant information. You can see the comments at
%the top of your M-file by typing 'help filename' at the MATLAB
%prompt.
%For practice, type the script below the dashed line in a blank
%text-file and save it with name FirstMfile.m in the current
%working directory of MATLAB. To display the first commented
%line go to the MATLAB prompt and type 'help FirstMfile' and
%press |Enter|. To execute the script type 'FirstMfile' and
%press |Enter|.
%-------------------------------------------------------------

10
%-----CREATING THE DATA TO BE PLOTTED-----
clear all
close all
t=[0:.015:10]';
DataA = (-t+10).*cos(6*t);
DataE = (-t+10).*cos(6*t + 1.5) + 1.2;
%-----FIRST GRAPH: BLUE LINE-----
subplot(2,1,1)
plot(t, DataA, 'b-')
grid on
%-----LABELS FOR THE FIRST GRAPH-----
xlabel('t (Units)')
ylabel('DataA (Units)')
%-----TITLE AND LEGENDS-----
title('DataA and DataE')
%-----SECOND GRAPH: RED X's-----
subplot(2,1,2)
plot(t, DataE, 'rx')
grid on
%-----LABELS FOR THE SECOND GRAPH-----
xlabel('t (Units)')
ylabel('DataE (Units)')

10

5
DataA (Units)

−5

−10
0 1 2 3 4 5 6 7 8 9 10
t (Units)

15

10
Datae (Units)

−5

−10
0 1 2 3 4 5 6 7 8 9 10
t (Units)

The basic difference between an m-file and a MATLAB function is just the very first line. The function will have
the following syntax for its first line of code:
function [r1, r2, r3, …] = FunctionName(a1, a2, a3, …)

a1, a2, a3, … are the arguments passed to the function FunctionName from the MATLAB
prompt. They go between parentheses ( ).

r1, r2, r3, … are the variables that the function will return; they must go between brackets [ ].

FunctionName is an arbitrary descriptive name for the function. To avoid confusion, it is


recommended that you give the same name to the m-file containing the script of the function. Study
carefully the following m-file representing a function called FirstFunction. This text would be
saved in a file called FirstFunction.m in the active directory.

11
MATLAB - FirstFunction.m
function [sumAB, prodtAB, AtoB] = FirstFunction(a, b)
%
%COMMENTS explaining what this function does, how to use it,
%examples, and any other relevant information.
%
sumAB = a + b;
prodtAB = a*b;
AtoB = a^b;

Now, observe below how we assign to the variables sum, prod, and pow the values returned by
the function FirstFunction.

MATLAB - Command Window


» [sum, prod, pow] = FirstFunction(2,3)
sum =
5
prod =
6
pow =
8

12

You might also like