Introduction to Matlab

Mathematics University of Queensland Mathematics

13  Larger Projects

In this section we show how Matlab is best used to do a more complicated assignment. It contains the following new ideas.

13.1  M-Files.

Script M-file or just M-files are plain text files containing Matlab code. For example, we may have 10 lines of Matlab code which computes results and then graphs the output. It is tedious to type in these 10 lines as we develop and change the code (even if we use the up arrow). However if we store the code in an M-file, say ass.m, then all the code in the file can be run by just typing in the file's name.

For example, let us place the following code from the 3D graphics section in the file ass.m. (Open the Matlab editor and type in the code. If you are reading the introduction on line, cut and paste the commands from the browser window to the editor. Save the file using the name ass.m.)

%                       This code goes 
%                       in the file  ass.m .
 
x=(-2:.1:2)' ;  y = (-2:.1:2)' ;
X, Y ] =  meshgrid(x,y) ; 
Z  =  X .* Y .* exp( -( X.^2 + Y.^2 ) ) ;
surf(X,Y,Z)
xlabel('X'); ylabel('Y'); zlabel('Z')

Now this code will be run by the single Matlab command

ass        % Run the code in the file  ass.m

If there are errors (there always are), we can quickly make corrections with our editor and run the code again. This is faster than repeatedly typing in the individual commands. M-files should be used if our task needs more than about 6 lines of Matlab.

Script M-files are similar to function files, but they do not contain the function statement at the beginning. Moreover, all the variables in the script M-file are the same as any variables appearing in the main Matlab command window. Thus running an M-file gives exactly the same result as if the code had been typed in from the keyboard. The names of these files must have the `.m' extension (e.g. `ass.m').

13.2  Some Programming

If x is an approximate square root of a, then it has long been known that
x¢ = 1
2
æ
ç
è
x+ a
x
ö
÷
ø
is general a better approximation. For example, starting with 1 and working with pencil and paper we have the following rational approximations to Ö2
1, 3
2
, 17
12
, 577
408
,¼
If we decide to stop after 20 approximations, this computation may be written formally as
x = 1
for k = 1,2,3,¼,20
            x = (x+ a
x
)/2
(8)
end
The third line in (8) does not mean x equals (x+a/x)/2, rather that the old value of x should be replaced with the new value (x+a/x)/2.

In practice we may have an accurate answer before we have computed all 20 new values of x. We could perhaps stop if x2-a is sufficiently small; but this is extra computation. Instead, we will stop when the new value of x is sufficiently close to the previous value, that is if the calculations are not changing the answer very much. Hopefully this means we are close to the true answer.

Formally our method becomes
x = 1
for k = 1,2,3¼,20
            x¢ = (x+ a
x
)/2
            if |x-x¢| £ 10-14 stop
(9)
            x = x¢
end

This can be coded in Matlab with a for statement, an if statement, and a break statement.

% Code to find sqrt(a)
x=1
for k=1:20
        xnew = (x+a/x)/2
    if abs(x-xnew) < =1.e-14, break, end
  x = xnew
end
    This code can go in the file mysqrt.m

Once we have typed the code into the file mysqrt.m, we can test the code in Matlab with the command

a = 2 ; mysqrt    % Run ysqrt with a=2
xnew, k           % The approximation to 2^.5 was found
                  % after  k steps.
xnew-sqrt(a)      % Check accuracy.

Because mysqrt is not a function, the value of a can be used by the commands in mysqrt. The results of the calculation can be found by looking at the values of k and xnew in the main Matlab command window. This is particularly useful in finding out what has gone wrong if something does not work.

Exercise 35

(a.)    Adjust the code so that no intermediate results are printed out.

(b.)    Run mysqrt with various values of a to complete the following table

a Computed Ö[] Steps needed Error in the approximation
2    
3    
4    
20    
1000    

Hint: To avoid retyping, use the following code.

tab = [ ] ; % tab contains the table of results
for a = [2 3 4 10 100 1000]
  mysqrt 
  err = xnew - sqrt(a);
  tab = [ tab ; a xnew k err ]; % The new results are added
end %  at the end of the table.

(c.)    Add a new first line to mysqrt to change it to a function m-file. The input argument should be the number a, the output argument should be the computed square root, xnew

(d.)    Alter the code so that mysqrt forms a table of values of k and xnew. Alter the function statement so that the function returns this table as a second output value.

13.3  More Programming

Matlab contains the usual variety of statements to control the flow of programs. Details of these may be found in the online documentation. From the Help Desk follow the link Getting Started then read about Flow Control.

In Matlab, traditional programming ideas using loops should be avoided. Suppose I wish to graph a function on [0,2]. Following the ideas of standard programs we could use the code

for i = 0:200
  x(i+1) = i/100 ;
  y(i+1) = cos(x(i)*pi) ;
end
plot( x,y,'-')

This is very, very slow, as well as being ugly and cumbersome. The elegant Matlab solution using component-wise operations is much nicer.

x = (0:.01:2)' ; plot( x, cos(x*pi), 'x')

13.4  Saving to Floppies.

To complete a big assignment you will need a number of sessions on the computer, and it is essential to keep a permanent copy of your programs and results from one day to the next. For this you will need at least one `double sided, high density, 3.5 inch' floppy disk; that is, one that can contain up to 1.44 Meg. These are obtainable at a number of shops on campus. (It is cheapest to buy a box of ten with 2 or 3 friends.) Please take sensible precautions against loosing your disks.

When Matlab is started the default directory is D:\TEMP, that is a directory on the internal hard disk. This means all files and results saved from within Matlab will be stored in this directory. Similarly Matlab looks for all M-files in this direcory. Unfortunately this directory is cleared when a new user logs on, and all work will be lost unless you remember to copy all files from D:\TEMP to your floppy. It is easy to forget to do this.

Thus it is better to make your floppy the default directory. Make your very first command in Matlab

  cd a:\     % This should be the first Matlab command
             %  Your floppy is now the default directory.

Then you always have a copy of your work on your disk. Now you only have to remember to take your floppy our of the drive before you go.