MEC500 Programming in MATLAB
MEC500 Programming in MATLAB
WITH APPLICATIONS
Programming in MATLAB:
Built in Functions
MATLAB has several built in functions that can do specific mathematical operations. You can use
it to great advantage by using them instead of writing your own.
For example sin, cos, ode45, ezplot, log, contour, etc
The actual functions you can use depends on the MATLAB toolboxes that are installed on the
computer where you will be running the piece of MATLAB code. It is recommended that you use
variable names that are not the same as the built in function names
To know what functions are available is essential before you can use it (they can be used only in
specified manner) or avoid defining variables with the same name. The help command is the best
resource to accomplish this
>> help elfun
% will display the elementary functions you can use
>> help specfun % will display special functions - bessel, gamma etc
Programming in MATLAB:
A lot of your creativity will be established using User Defined Functions (UDF).
There is some necessary syntax (rules) involved. Here is an example
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 c=campur(a,b)
% c=campur(a,b). This program adds a to b.
c=a+b;
You should make a file named campur.m and enter this program exactly as it is written. Now
assign some integer values for a and b. Run
campur(a,b)
This should run just like any built-in MATLAB function. Type
and
help campur
type campur
Branching
Branching is the construction
if <condition>, <program> end
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
Programming in MATLAB:
If statements
if
2.
if
3.
if
expression_1
statements
% executed if expression_1 is true
elseif expression_2
statements
% executed if expression_2 is true
elseif expression_3
.......................
else
statements
end
Programming in MATLAB:
If statements - code
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
Programming in MATLAB:
Switch/Case Statement
If you need to execute different commands for different results based on a single condition then
the switch/case is the control you need
switch expression % can be a scalar or a string
case test1
command set 1
case test 2
command set 2
......................................
otherwise
command set last
end
If expression is scalar then case is executed if the scalar value matches the expression in the
test
If expression is string then case is executed if the strings match
Programming in MATLAB:
Code
Switch/Case Statement -
x = 3.0;
% numeric variable
units = 'mm';
% string variable
switch units
case {'in','inch'}
% multiple matches
y = 2.54*x;
% converts to centimeters
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
% disp is used to print pretty in the command window
% in the above a string vector is being printed
case {'m','meter'}
y = x*100;
% converts to centimeters
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case { 'millimeter','mm'}
y = x/10;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case {'cm','centimeter'}
y = x;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
otherwise
disp (['unknown units:' units])
y = nan; % not a number
end
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
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=campur(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
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,
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
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).
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
Programming in MATLAB:
For (loop)
Programming in MATLAB:
A=[1 2 3; 4 5 6]
for n = 1: length(A(1,:)) % length of first row
% default stepsize = 1
xa(n) = A(1,n)^2;
for m = 1:2:length(xa) % note in steps of 2
m
X(n,m) = n*m;
% whats happenning here?
% how will you check whats happenning ?
end
end
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
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)
Programming in MATLAB:
While (loop)
The while statement allows execution of a block of statements as long as the expression is true
If the statements do not modifythe expression then you have an infinite loop
while expression
statements
end
you can use a break statement to exit the loop prematurely
while loops can be nested
Programming in MATLAB:
count = 1; num = 2;
while count < 16
cnum= [count num]
disp(cnum)
num = num*2;
count = count + 1;
if count >= 10
break
end
end
% forms a vector
% pretty printing
% expression is modified
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
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.
behave if condition=eye(2)? The program1 will execute if all of the entries of condition are
not 0. Thus if condition=magic(2), program1 will execute while if condition=eye(2) control
will pass to the "else" part and program2 will execute.
A problematic construction occurs when you have
if A ~= B, <program>, end.
You would like program to execute if the matrices A and B differ on some entry. Under the
convention, program will only execute when they differ on all entries. There are various ways
around this. One is the construction
if A ==B
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
which will pass control to the "else" part if A and B differ on at least one entry. Another is to
convert A==B into a binary valued function by using all(all(A==B)). The inside all creates a
binary vector whose i--th entry is 1 only if the i--th column of A is the same as the i--th
column of B. The outside all produces a 1 if all the entries of the vector are 1. Thus if A and B
differ on at least one entry, then all(all(A==B))=0. The construction
if ~ all(all(A==B)), <program>, end
The program program will execute successively as long as every entry in condition is not 0,
and the control passes out of the loop when at least one entry of condition is 0.
Another problem occurs when you have a conjunction of conditions, as in
if <condition1> & < condition2>,
<program>, end
Of course, program will execute if both condition1 and condition2 are nonzero. Suppose that
condition1=0 and condition2 causes an error message. This might happen for
i<=m &
A(i,j)==0
where m is the number of columns of A. If i>m, then you would like to pass the control, but
since A(i,j) makes no sense if i>m an error message will be dished up. Here you can nest the
conditions.
if i<=m,
if A(i,j)==0,
<program>
end
end
Scripts
A script is an m-file without the function declaration at the top. A script behaves differently.
When you type who you are given a list of the variables which are in force during the current
session. Suppose that x is one of those variables. When you write a program using a function
file and you use the variable x inside the program, the program will not use the value of x
from your session (unless x was one of the input values in the function), rather x will have the
value appropriate to the program. Furthermore, unless you declare a new value for x, the
program will not change the value of x from the session. This is very convenient since it
means that you do not have to worry too much about the session variables while your
program is running. All this has happened because of the function declaration. If you do not
make that function declaration, then the variables in your session can be altered. Sometimes
this is quite useful, but I usually recommend that you use function files.
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
10
Suggestions
These are a few pointers about programming and programming in MATLAB in particular.
1) I urge you to use the indented style that you have seen in the above programs. It makes the
programs easier to read, the program syntax is easier to check, and it forces you to think in
terms of building your programs in blocks.
2) Put lots of comments in your program to tell the reader in plain English what is going on.
Some day that reader will be you, and you will wonder what you did.
3) Put error messages in your programs like the ones above. As you go through this manual,
your programs will build on each other. Error messages will help you debug future programs.
4) Always structure your output as if it will be the input of another function. For example, if
your program has "yes-no" type output, do not have it return the words "yes" and "no," rather
return 1 or 0, so that it can be used as a condition for a branch or while loop construction in
the future.
5) In MATLAB, try to avoid loops in your programs. MATLAB is optimized to run the builtin functions. For a comparison, see how much faster A*B is over mult(A,B). You will be
amazed at how much economy can be achieved with MATLAB functions.
6) If you are having trouble writing a program, get a small part of it running and try to build
on that. With reference to 5), write the program first with loops, if necessary, then go back
and improve it.
Further details on MATLAB may be obtained from the following sources.
1.
2.
http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
Source: http://www.math.ufl.edu/help/matlab-tutorial/index.html#SEC19
11