
Lab visit July 3, 2002
Warning: I use Matlab 4.0, an ancient version. There have been changes and you may need to make use of the help command.
The purpose of this note is to introduce you to using Matlab interactively and also to do a bit of Matlab programming. Many features of Matlab, even commonly used ones, will be omitted.
When you start Matlab a window, the command window, opens up. You can type interactive commands in the command window. Editing is a bit primitive, but functional. Cursor up may be used to recall previous commands (in the current session).
Matlab commands are terminated by a newline (that is, pressing the Enter key if you are working at the Matlab command line). Several commands may be stacked up on one line by separating them by commas. Matlab's line continuation character is ... This is useful spreading long commands over several lines.
Matlab's assignment operator is the equals sign =. The test for equality is the doubled equals sign ==.
|
The command
>> help
returns a list of topics for which help is available. The command
>> help exp
returns help on the exp function. You may find the command
>> help help
very instructive (but make sure the pager is enabled). For information on the pager (more) try
>> help more
If the pager is enabled you may step through pages of help text by pressing the space bar. You can also step through the text line by line by pessing the enter key. To quit paging through help text just enter a "q."
Matlab commands are contained in m files, one per file (until recently), or are entered interactively at the Matlab prompt, >>.
A list of the directories where Matlab searches for m files can be obtained by the command
>> path
One of the directories in which Matlab always looks is the current working directory; the command
>> cd
identifies the current working directory. You can also use
>> pwd
to get the current working directory. The command
>> cd z:\
changes the working directory to z:\ which is probably a good idea if you are working in the MLC lab. Files saved on z:\ will be visible no matter what lab computer you are using.
The command
>> dir
returns a list of files in the current working directory. You can also use the command
>> ls
Many commands in Matlab have both MSDOS and UNIX style versions. To get a rapid introduction to Matlab and some feeling for what it can do, try the command
>> demo
The demos will keep you busy for quite some time.
Any discussion of Matlab data types is bound to be short. Matlab has essentially only one data type - the array. Let's create a 2-by-2 matrix
>> A = [1 2; 3 4]
A =
1 2
3 4>> A^2
ans =
7 10
15 22
Sure enough this is the square of the matrix A. Now try
>> A.^2
ans =
1 4
9 16
What happened? This is a Matlab idiom - an important one. The dot before a command (let's try to refrain from calling it a dot com) causes Matlab to carry out the command componentwise. That is, each entry in A was squared, rather than A being squared. The dot commands are called array commands, whereas the standard linear algebra commands are called matrix commands.
It is not always completely obvious what an array command will do. For example,
>> B = [3 7; 1 -2], A.^B
B =
3 7
1 -2
ans =
1.0000 128.0000
3.0000 0.0625
We can recall the value of A by simply entering A. Thus
>> A, exp(A), expm(A)
A =
1 2
3 4ans =
2.7183 7.3891
20.0855 54.5982ans =
51.9690 74.7366
112.1048 164.0738
Here the first matrix returned is A. The second is exp(A) which computes the exponential of each entry in A, whereas expm(A) computes the exponential of the matrix A. Thus exp() is an array operation while expm() is the familiar matrix operation traditionally denoted by exp(). Be careful!
Try
>> help exp expm
to get information on both commands.
While it is possible to do quite a bit with Matlab by just entering commands at the Matlab prompt it is troublesome if you discover that you made an error several steps back. You can use the up and down arrow keys to step through your commands, but this is hardly satisfactory. The best solution is to use m-files.
There are basically two kinds of m-files: scripts and functions.
A script m-file consists of a sequence of commands which are carried out when the script is loaded by typing its name at the command prompt. Be very careful! The main purpose of a script is to add a number of definitions to your workspace, or to carry out a sequence of commands. Everything defined in the script becomes part of your workspace. Variables may be overwritten silently.
A function m-file is an m-file which accepts parameters (including the empty set). Functions generally communicate with the command window through input and output parameters. Global variables are also available, but should be used sparingly. All other variables are local to the m-file and are not "visible" in the command window. In particular, they do not overwrite variables of the same name in the command window.
To create a new m-file open the file menu and select new. An editor window will open up. When you are done, save the file (with the file extension .m). The editor will save the file to your current default directory as set in Matlab. If you already set your default directory that's fine, but you should still check carefully to make sure you are saving to an appropriate personal file location.
A function m-file always starts with the statement declaring it to be a function m-file. Typically the statement looks like this
function[output parameters] = fname(input parameters)
The parameters are separated by commas. The square brackets may be omitted if there is only one output parameter.
The square brackets and the equals sign may be omitted if there are no output parameters (for example, a special plot routine).
In an m files any line preceeded by a percent sign (%) is treated as a comment. The first consecutive group of comment lines is returned by the help command. This feature is very useful!
Here is an example m file. It computes and displays the polynomial least squares fit for a given data set. It is a very simple combination of commands already available in Matlab. Be sure to use help to look up each of them. You can download this m-file as lsp.m
========== this file must be saved as lsp.m ==========
function lsp(Xdata,Ydata,deg,xplot)
% Given data points Xdata and Ydata this routine plots
% the least squares fit polynomial of degree deg. The
% plot of the polynomial is performed at the abscissas
% given by xplot.
% Mth 355 Fall 2001
% The declaration
%
% function lsp(Xdata,Ydata,deg,xplot)
%
% shows this m-file returns no value.
p = polyfit(Xdata,Ydata,deg);
q = polyval(p,xplot);
plot(xplot,q,'c',Xdata,Ydata,'oy')
========== end of lsp.m ==========
Once you have saved this m-file then it may be executed. In addition the help command automatically knows about it:
>> help lsp
Given data points Xdata and Ydata this routine plots
the least squares fit polynomial of degree deg. The
plot of the polynomial is performed at the abscissas
given by xplot.
Mth 355 Fall 2001
Note the second set of comment lines is not returned by the help command because they are seperated from the first set by a blank line. If you want to include the second set you can simply put a % sign at the beginning of the blank line.
Note how the plot() command can handle several plots. The 'c' specifies the color cyan, the 'oy' specifies little circles in yellow. Sometimes though you do not want to combine all plots in one command, or perhaps one of your plot commands is stem() (try help stem for more information) and you don't see how to combine it with regular plot() commands. In that case you can use hold (hold on and hold off - check help hold) to combine plots.
Let's check our lsp command:
>> X1=[-1.2 -0.8 -0.9 -0.2 0 0.5 1.1 1.9 2.3 3.4];
>> Y1=[ 2.2 2.3 2.4 1.9 2.1 2.2 2.4 1.7 1.1 0.8];
>> xp1=linspace(-1.2, 3.4, 30);
>> lsp(X1,Y1,5,xp1)
Note the use of semicolons to suppress useless output.
The linspace command above creates a list of 30 points equally spaced from -1.2 to 3.4. It is very a very useful command. Have you tried "help linspace" yet?
If you are very attentive you may have noted that the colors in the image do not match what was requested. That is because I edited the image to make it easier to see.
There is still a lot to learn about 2D graphics, but let's jump ahead to 3D graphics. Matlab has a reputation for being able to produce acurate and beautiful 3D graphics.
Here is a sample space curve
>> t=pi/30:pi/60:20*pi ;
>> plot3(t.*cos(t),t.*sin(t),log(t))
>> title('Conical Helix with log rise'), xlabel('x=t*cos(t)')
>> ylabel('y=t*sin(t)'), zlabel('z=log(t)')
The first command creates a list from pi/30 to 20*pi with stepsize pi/60. In the plot3() comamnd note that cos(t), etc., means create a list by computing the cosine at each point in the list t. That is why there is a dot in the expression t.*cos(t) - we want to multiply the list (or array) t with the list cos(t) componentwise. The next four commands, two per line (separated by commas), annotate the image in the current plot window.

Note the plot command clears plot image window, resets defaults and then draws the new plot. Subsequent commands (such as title) annotate the current plot image. To combine several plots in one image use the "hold on" command as mentioned above. Check "help hold."
Once you have a nice graphic you may wish to save it for use in another application. The command
>> print -depsc2 filename.eps
will produce a full-color encapsulated Postscript file image of your current plot window (you select a name to use in place of "filename" of course). The command
>> print -dmfile filename.m
will create an m-file which can be run to re-create your plot. This is handy if you are deep into an interactive session. The command
>> print -dmeta
will export the image in the current plot window to the Windows Clipboard (on Windows machines) as a Windows Metafile. It can then be pasted into almost any graphics application (I use Paint Shop Pro), touched up and converted as you see fit. You can use -dbitmap instead if your graphics application does not use Metafiles.
Here is an m-file to compute fixed point iterates for the logistic equation.
===== this file must be saved as logistic.m =====
function y = logistic( c,x,n )
% This function computes fixed point iterates of
% f(x) = c*x*(1-x). It is assumed that c is a
% scalar (between 0 and 4) and n-1 is the number
% of iterates to compute.
% The initial point(s) x may be a row vector and
% appears as the first row in the output.
% Mth 351 Summer 2002
y = zeros(n,size(x,2)); % size(x,2) is num cols in x
y(1,:) = x;
for k = 2:n;
y(k,:) = c*y(k-1,:).*(1.-y(k-1,:));
end
% End logistic.m
=================================================
To convince you it works here is some sample output:
>> x = linspace(0,1,9); x=x(2:8)
x =
0.1250 0.2500 0.3750 0.5000 0.6250 0.7500 0.8750
>> logistic(0.8,x,12)
ans =
0.1250 0.2500 0.3750 0.5000 0.6250 0.7500 0.8750
0.0875 0.1500 0.1875 0.2000 0.1875 0.1500 0.0875
0.0639 0.1020 0.1219 0.1280 0.1219 0.1020 0.0639
0.0478 0.0733 0.0856 0.0893 0.0856 0.0733 0.0478
0.0364 0.0543 0.0626 0.0651 0.0626 0.0543 0.0364
0.0281 0.0411 0.0470 0.0487 0.0470 0.0411 0.0281
0.0218 0.0315 0.0358 0.0370 0.0358 0.0315 0.0218
0.0171 0.0244 0.0276 0.0285 0.0276 0.0244 0.0171
0.0134 0.0191 0.0215 0.0222 0.0215 0.0191 0.0134
0.0106 0.0150 0.0168 0.0173 0.0168 0.0150 0.0106
0.0084 0.0118 0.0132 0.0136 0.0132 0.0118 0.0084
0.0067 0.0093 0.0104 0.0108 0.0104 0.0093 0.0067
Here each column is the sequence of iterates with initial point given by the corresponding component in x (which also occurs in the first row). Since c = 0.8 were are in the contractive regime for the logistic function and we expect to see moderately rapid covergence to 0.
>> clear x
removes the variable or function x from your workspace, wheras
>> clear
or
>> clear variables
removes all variables and
>> clear functions
removes all compiled functions. (The first time you use an m-file it is compiled and becomes part of your current work space.)
>> clear all
removes all functions and variables from your workspace and gives you a more or less fresh start.
>> who
or better
>> whos
will list all your current variables.
The functions ones(), zeros() and eye(n) are used to create special matrices. Check help and save me some typing!
>> clear x
>> for n = 1:6
x(n) = 3^n ;
end
>> x
x =
3 9 27 81 243 729
Many traditional for loops may be replaced by Matlab's array operations. Thus
>> x = 3.^[1:6]
x =
3 9 27 81 243 729
There is a difference between these two commands. In the for loop we are assigning values to components of x. Thus if x already was defined 1 by 10 array only the first 6 components would be changed. The rest would remain. That is why I cleared x firs. In the second command we assign x as a 1 by 6 array. If it was already defined as something else, it is now redefine.
Note - try to get used to the Matlab idiom. Thus
>> [1:6].^3
ans =
1 8 27 64 125 216
That is, we cube each entry in [1:6] == [ 1 2 3 4 5 6 ].
Let see how many terms of the harmonic series we need to add up to get a sum of 6 or more.
>> s = 1; n = 1;
>> while s < 6
n = n +1 ;
s = s+1/n ;
end
>> n
n =
227
If structures follow the same pattern as in other programming languages. All you need to know really is the keywords are if elseif else end and there is no then. To test for equality use == and to test for inequality use ~=.
A polynomial is represented by its coefficients. Thus 3 x^4 - 2 x^3 + x - 5 is represented by
>> p = [3 -2 0 1 -5 ]
p =
3 -2 0 1 -5
Matlab is very good at finding roots of polynomials
>> roots(p)
ans =
0.2249 + 1.0920i
0.2249 - 1.0920i
1.2714
-1.0545
To multiply two polynomials (as polynomials) use the conv() command. Thus
>> q = [ 3 1 4]
q =
3 1 4
>> r = conv(p,q)
r =
9 -3 10 -5 -14 -1 -20
As we saw above, in lsp.m, polyval() is used to evaluate polynomials and to plot polynomials. For example,
>> x = linspace(-2,2,60) ; % 60 points
>> y = polyval(p,x) ; % evaluation at points in x
>> ax = zeros(1,60) ; % 60 points for x-axis
>> plot(x,ax,'g-.') % plot x-axis in green
>> hold on
>> plot(x,y,'r') % plot polynomial in red
>> hold off
>> title('polynomial plot')
>> xlabel('x axis')
>> ylabel('y axis')

Be sure to check fplot() if you want to get good plots as automatically as possible.
===== this file must be saved as sinax.m =====
function y = sinax( x )
y = sin(x)-0.4*x;
==============================================
After saving the m-file sinax.m listed above try the plot command
>> fplot('sinax',[0,3])
It is clear that there is a root near 2. The fzero command should find it
>> fzero('sinax',2)
ans =
2.1253
Note how we tell Matlab to search for a root near 2.
The single quotes on sinax above for fplot are not needed in all versions of Matlab. Perhaps later versions of Matlab also do not require them for the fzero call.
Problem: Implement Newton's method and use it to approximate the nonzero root of sinax. Likewise use the secant method and the bisection method. If you want to write fairly general purpose root finding routines you will have to pass a function name as an argument to your routines. This can be done by using the feval command. Check help feval or the example on page 266 of our text. If you don't care about generality you can hardwire the function sinax. See our text page 264 for an example.