Thursday, 17 March 2011

Programming in MATLAB

Programming in MATLAB

MATLAB is also a programming language. By creating a file with the extension .m you can easily write and run programs. If you were to create a program file myfile.m in the MATLAB language, then you can make the command myfile from MATLAB and it will run like any other MATLAB function. You do not need to compile the program since MATLAB is an interpretative (not compiled) language. Such a file is called an m-file.
I am going to describe the basic programming constructions. While there are other constructions available, if you master these you will be able to write clear programs.

Assignment

Assignment is the method of giving a value to a variable. You have already seen this in the interactive mode. We write x=a to give the value of a to the value of x. Here is a short program illustrating the use of assignment.


function r=mod(a,d)

% r=mod(a,d). If a and d are integers, then
% r is the integer remainder of a after 
% division by d. If a and b are integer matrices,
% then r is the matrix of remainders after division
% by corresponding entries. Compare with REM.

r=a-d.*floor(a./d);   
You should make a file named mod.m and enter this program exactly as it is written. Now assign some integer values for a and d. Run
mod(a,d)
This should run just like any built-in MATLAB function. Type
help mod
This should produce the five lines of comments which follow the % signs. The % signs generally indicate that what follows on that line is a comment which will be ignored when the program is being executed. MATLAB will print to the screen the comments which follow the "function" declaration at the top of the file when the help command is used. In this way you can contribute to the help facility provided by MATLAB to quickly determine the behavior of the function. Type
type mod
This will list out the entire file for your perusal. What does this line program mean? The first line is the "function declaration." In it the name of the function (which is always the same as the name of the file without the extension .m), the input variables (in this case a and d), and the output variables (in this case r) are declared. Next come the "help comments" which we have already discussed. Finally, we come to the meat of the program.
The variable r is being assigned the value of a-d.*floor(a./d); The operations on the right hand side of the assignment have the meaning which you have just been practicing (the / is division) with the "." meaning the entry-wise operation as opposed to a matrix operation. Finally, the ";" prevents printing the answer to the screen before the end of execution. You might try replacing the ";" with a "," and running the program again just to see the difference.

Branching

Branching is the construction
if <condition>, <program> end
The condition is a MATLAB function usually, but not necessarily with values 0 or 1 (later I will discuss when we can vary from this requirement), and the entire construction allows the execution of the program just in case the value of condition is not 0. If that value is 0, the control moves on to the next program construction. You should keep in mind that MATLAB regards a==b and a<=b as functions with values 0 or 1.

Frequently, this construction is elaborated with

if <condition1>, <program1> else <program2> end
In this case if condition is 0, then program2 is executed.
Another variation is

if <condition1>, <program1> 
elseif <condition2>, <program2>
end

Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is not 0, then program2 is executed, and otherwise control is passed on to the next construction. Here is a short program to illustrate branching.


function b=even(n)

% b=even(n). If n is an even integer, then b=1
% otherwise, b=0.

if mod(n,2)==0,
   b=1;
   else b=0;
end

For Loops

A for loop is a construction of the form
for i=1:n, <program>, end
Here we will repeat program once for each index value i. Here are some sample programs. The first is matrix addition.


function c=add(a,b)

% c=add(a,b). This is the function which adds 
% the matrices a and b. It duplicates the MATLAB 
% function a+b.

[m,n]=size(a);
[k,l]=size(b);
if m~=k | n~=l,
   r='ERROR using add: matrices are not the same size';
   return, 
end
c=zeros(m,n);
for i=1:m,
   for j=1:n,
      c(i,j)=a(i,j)+b(i,j);
   end
end

The next program is matrix multiplication.


function c=mult(a,b)

% c=mult(a,b). This is the matrix product of 
% the matrices a and b. It duplicates the MATLAB 
% function c=a*b.

[m,n]=size(a);
[k,l]=size(b);
if n~=k, 
   c='ERROR using mult: matrices are not compatible 
      for multiplication',
   return,
end,
c=zeros(m,l);
for i=1:m,
   for j=1:l,
      for p=1:n,
         c(i,j)=c(i,j)+a(i,p)*b(p,j);
      end
   end
end

For both of these programs you should notice the branch construction which follows the size statements. This is included as an error message. In the case of add, an error is made if we attempt to add matrices of different sizes, and in the case of mult it is an error to multiply if the matrix on the left does not have the same number of columns as the number of rows of the the matrix on the right. Had these messages not been included and the error was made, MATLAB would have delivered another error message saying that the index exceeds the matrix dimensions. You will notice in the error message the use of single quotes. The words surrounded by the quotes will be treated as text and sent to the screen as the value of the variable c. Following the message is the command return, which is the directive to send the control back to the function which called add or return to the prompt. I usually only recommend using the return command in the context of an error message. Most MATLAB implementations have an error message function, either errmsg or error, which you might prefer to use.
In the construction

for i=1:n, <program>, end 

the index i may (in fact usually does) occur in some essential way inside the program. MATLAB will allow you to put any vector in place of the vector 1:n in this construction.
Thus the construction

for i=[2,4,5,6,10], <program>, end 

is perfectly legitimate. In this case program will execute 5 times and the values for the variable i during execution are successively, 2,4,5,6,10. The MATLAB developers went one step further. If you can put a vector in, why not put a matrix in? So, for example,

for i=magic(7), <program>, end 

is also legal. Now the program will execute 7 (=number of columns) times, and the values of i used in program will be successively the columns of magic(7).

While Loops

A while loop is a construction of the form

while <condition>, <program>, end

where condition is a MATLAB function, as with the branching construction. The program program will execute successively as long as the value of condition is not 0. While loops carry an implicit danger in that there is no guarantee in general that you will exit a while loop. Here is a sample program using a while loop.


function l=twolog(n)

% l=twolog(n). l is the floor of the base 2
% logarithm of n.

l=0;
m=2;
while m<=n
   l=l+1;
   m=2*m;
end

Recursion

Recursion is a devious construction which allows a function to call itself. Here is a simple example of recursion

function y=twoexp(n)

% y=twoexp(n). This is a recursive program for computing
% y=2^n. The program halts only if n is a nonnegative integer.

if n==0, y=1;
   else y=2*twoexp(n-1);
end

The program has a branching construction built in. Many recursive programs do. The condition n==0 is the base of the recursion. This is the only way to get the program to stop calling itself. The "else" part is the recursion. Notice how the twoexp(n-1) occurs right there in the program which is defining twoexp(n)! The secret is that it is calling a lower value, n-1, and it will continue to do so until it gets down to n=0. A successful recursion is calling a lower value.

There are several dangers using recursion. The first is that, like while loops, it is possible for the function to call itself forever and never return an answer. The second is that recursion can lead to redundant calculations which, though they may terminate, can be time consuming. The third danger is that while a recursive program is running it needs extra space to accomodate the overhead of the recursion. In numerical calculations on very large systems of equations memory space is frequently at a premium, and it should not be wasted on program overhead. With all of these bad possibilities why use recursion? It is not always bad; only in the hands of an inexperienced user. Recursive programs can be easier to write and read than nonrecursive programs. Some of the future projects illustrate good and poor uses of recursion.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...