Professional Documents
Culture Documents
Matlab Intro Marsh
Matlab Intro Marsh
Matlab Intro Marsh
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.
§ 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.
§ 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.
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.
»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:
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:
2
Assigning the entire 3rd row of the M matrix to the row vector m_3 is done by:
Assigning the 2nd column of the M matrix to the column vector m_2 is done by:
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.
»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:
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):
Transposing a matrix A:
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:
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.
4
Square root sqrt(4) = 2
Going back to our previous examples, let us save the last two variables R and P to a file called
rootpoly.
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.
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.
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).
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.
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.
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:
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.
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:
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.
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:
For the following example we plot a blue dotted line with red X markers on top:
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.
§ 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.
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.
§ 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 [ ].
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.
12