Lab 10
MATLAB II





Lab 6 gave a basic introduction to MATLAB, but it did not cover some of the more powerful features of MATLAB.


Objectives for this lab:

  1. Symbolic Expressions
  2. Conditionals
  3. Interation
  4. Recursion in MATLAB



Symbolic Expressions

MATLAB stores equations as character strings. For example, let's look at the following polynomial:
 

You can enter this equation into MATLAB by assigning it to a variable. You can call it S1:

S1 = 'X^2 + 5*X + 3';

Differentiate
Now that the equation is in MATLAB, we can apply various operations to it. First, we shall differentiate it:
 diff(S1,'X')


This tells MATLAB to differentiate with respect to X. It should return
2X + 5


Integrate
Now let's integrate it:
int(S1,'X',1,100)


Here the 1 and 100 are the limits of integration. They are optional. The command should return
717255/2


Let us enter another equation:

S2 = 'X^2-X-6=0';

Note that this time we have set the function equal to a value.



Solve
Now let's try to solve that equation
solve(S2)
MATLAB will return [ 3] and [-2].
Solve can do many different things. You should use the help command on solve to see all the ways you can use it.



Square
Let us try to square S1. One function that might be useful is the sympow function, which raises an equation to a power. We will try that first:
sympow(S1,2)


Unfortunately, that just returns
(X^2+5*X+3)^2


Expand
Although that expression is true, it is not very revealing. We really need to tell MATLAB to expand that for us:
expand(sympow(S1,2))


This is much better...
X^4+10*X^3+31*X^2+30*X+9



Simplify
Next let's try to simplify an expression. Try entering:
S3 =  expand(sympow(S1,2));


and to simplify S3, use the simple command:
simple(S3)


You will see:
ans =
(X^2+5*X+3)^2
The nice thing is that MATLAB shows you each step it takes to get the equations from one form to the next.

Factor
Finally, we will try to factor something:
S4 = 'X^3-1';
factor(S4)
This returns:
ans =
(X-1)*(X^2+X+1)



Again, MATLAB offers many more symbolic functions. Use help to see what each function does. You can also type help on a line by itself, and MATLAB will give you list of places you can look for new commands to try.



More MATLAB Scripting

In the last MATLAB lab, you learned about scripting, but the functions that were created could not do very much. Like scheme, MATLAB functions can contain conditionals, iteration, and use recursion.

Conditionals in MATLAB are closer to the use of cond in scheme. A conditional begins with an 'if' and ends with 'end'. Below is an example of the use of if:



If statement

d=20;

if d > 100 
        disp('Greater than 100'); 
elseif d > 10 
        disp('Greater than 10'); 
else 
        disp('Less than 10'); 
end 
Notes about if statements:
In addition to conditionals, iteration and recursion (which you should be familiar with now) can be used within a function.



Iteration

For loop:

for k=100:-1:1 
    disp(k); 
end 
This example will print out the numbers 100 to 1 by counting down.
Notes about for loops:
<starting value>:<increment by>:<ending value>
If you leave out the "increment by" value, it is assumed to be 1.


While loop

while (x>0) 
      disp(x); 
      x=x-1; 
end 
x>0 is your test expression.
The statements in between the while and end lines can be anything you want to do in the while loop.
All while loops end with the keyword end, as in the example.
Notes about while loops:
You must initialize your control variable (in the above example, x) before you start the while loop. In other words, x must be an input variable, or you must have a separate assignment line such as
x = 10;
before the while loop starts.


MATLAB Relational and Boolean Operators:

Less than <
Less than or equal to <=
Greater than >
Greater than or equal to >=
Equal ==
Not equal ~=
And &
Or |
Not ~



Recursion

Recursion is very easy in MATLAB. All you have to do is call your function somewhere in your script. You call your function as you would any other MATLAB function. If you are still confused, here is a very simple example that will print out a text string a certain number of times (based on an input parameter):


function [] = example(x)
% example(x) 
% Prints out the string "Listen to Billy and call the doctor." x times 
if x > 0 
      disp('Listen to Billy and call the doctor.'); 
      example(x-1); 
end 

For this script to run, save it in a file called "example.m". As for the script itself, it takes in one input variable and returns nothing. As the script starts, it checks the value of x. If x is greater than zero, it prints out the string, and calls itself again (recursion). Notice that when the function occurs, the value of x is reduced. This is to ensure that we approach a terminating condition (in this case, when x is no longer greater than 0). You should always make sure your recursive scripts approach termination; infinite recursion will crash your computer in record time!



Recursion and Iteration: An Example

Listed next are two example functions, one recursive and one iterative, each of which accepts two values and computes the greatest common denominator (GCD). Before you look at the functions, an explanation of GCD is in order.

The greatest common denominator (GCD) of two numbers is the largest integer that can be evenly divided (leaving no remainder) by both numbers. For example, the GCD of 15 and 5 (written as gcd (15, 5)) is 5 because 5 is the largest number that is divided evenly by 15 and 5. Some more examples:

gcd (24, 12) = 12

gcd (13, 2) = 1

gcd (110, 85) = 5
One way of finding the GCD of any two numbers is called the Euclidian method. With the Euclidian method, you set up three columns, labeled X, Y, and Remainder. In "X", the first number is placed; in "Y", the second number. The remainder that occurs when X is divided by Y is placed in the "Remainder" column. If the remainder is 0, then whatever is in column Y is the greatest common denominator. If the remainder is not 0, a new row in the table is created. The previous row's Y value is placed in the X column, and the previous row's remainder goes in the Y column. The remainder is then computed again, and is placed in the "Remainder" column. This process repeats until 0 is the remainder.

Consider this example of computing the GCD of 110 and 85
X Y Remainder

110 85 25
85 25 10
25 10 5
10 5 0

This process is rather tedious, and can be greatly aided by a computer.



Example Recursive Function

Here is the recursive solution. Notice that all lines with a single equals sign end with a semicolon. This is to prevent unnecessary output being displayed to the screen. Also notice the function is called rGCD, the r indicating recursion.
function [ result ] = rGCD(x, y) 
% rGCD(x,y) returns the greatest common denominator of x and % y 
temp = mod(x, y); 
if ( temp == 0) 
     result = y; 
else 
     result = rGCD(y, temp); 
end 


Example Iterative Function

To stick with the above naming convention, the function is named itGCD, where the 'it' indicates a loop.
function [ result ] = itGCD(x, y) 
% itGCD(x,y) returns the greatest common denomonator of x and % y 
temp = mod(x, y); 
while ( temp > 0) 
     x = y; 
     y = temp; 
     temp = mod(x, y); 
end 
result = y; 
Here's a reminder of the syntax for a function:
function [<any variables you want to be returned, separated by commas>] = <functionName>(<parameter list>)
% Percent signs are comment marks.
<All of your statments for this function>

Functions just end. There's no special way to make it end. If you want something printed out to the screen, don't but a semicolon after it. If you do not want something printed out to the screen, make sure there's a semicolon after that statement.


Your Assignment

What you need to turnin:

  1. Write a function called rfib which RECURSIVELY computes the fib of a number.---- Save it in file called rfib.m
  2. Write a function called itfib which iteratively computes the fib of a number.---- Save it in file called itfib.m
  3. Write the mod function using recursion and save it in a file called rmod.m
  4. Write the mod function using iteration and save it in a file called itmod.m

The mod function if similar to the remainder function, but not exactly the same. Try the mod function in MATLAB to see the differences. Web pages also help.

Turnin all of these files by 8 a.m., Monday, Mar. 26,2001. Turn in the following files:

rfib.m itfib.m rmod.m itmod.m