CS1321 - Lab 4
MATLAB

Due Before 8:00am, Sunday November 11, 2001
(see turnin information below)


What Is MATLAB?

The name MATLAB stands for "matrix laboratory". MATLAB was originally written to provide easy access to matrix software developed by the LINPACK and EISPACK projects. These projects represented the state of the art in software for matrix computation. MATLAB is an interactive programming system for scientific and engineering numeric calculation. It is especially good with matrices, but works well with scalars too. MATLAB also works as an interpreted programming language. Since anyone can write new functions at any time, it is highly extendible. Also, large libraries of function already exist and are available on the web. One great resource for already written and tested functions is the Mathworks Website (Mathworks is the company that makes MATLAB).


MATLAB Versions

Current Versions

Since MATLAB 6 just came out recently, it is not yet available in all of the labs on campus (and is not yet "stable" on all OS's) as such you can use EITHER version 5 or 6 to complete this lab. The differences (other than cosmetic ones) are minor. If you're using MATLAB 6, you'll notice that it has a new user interface with two extra windows; however, the interactions window (on the left) is the same as the main window in MATLAB 5.

Student Versions

Inevitably someone will ask what the differences are between the regular version and the student version of MATLAB, so here they are:

So in conclusion, for this lab you can use either MATLAB 5 or MATLAB 6 and either standard or educational (student) versions and use your choice of OS (Windows, MacOS, Unix). And if you follow what we show you here, your lab will work on all of these versions without any problems. Ain't that great?


Using MATLAB

Basic use

Once you start MATLAB, you can use it similar to the scheme interpreter. For example, first try this:

>> 3


MATLAB Returned:

ans =
     3


The first thing you probably notice is that it has assigned the result to a variable named "ans". MATLAB evaluates the expression and then assigns the result to something, so if you don't specify where to assign it, MATLAB will put it in "ans". Simple math in MATLAB is different from scheme because it evaluates simple math operators using infix notation. Try this:

>> 7 * 3


MATLAB Returned:

ans =
     21


MATLAB is case sensitive; so, pick one way to capitalize variable names and stick to it.

How do you find out the value of a given variable? The same way you do it in Scheme, type the variable's name in at the command prompt. Like this:

>> ans


Printing to the Screen

The easy way to print to the screen in a nice "uncluttered format" is with the "disp" command (short for display). To print the value of a variable using "disp", you would type (note that, while Scheme used double quotes ["..."] to indicate a string, MATLAB uses single quotes ['...']):

>> disp('The answer is'); disp(ans)


MATLAB will return:

The answer is
    12


Note how we put both commands on the one line separated by a semicolon. This tells MATLAB to execute both of them together without prompting you in between.

Use of the semicolon

In the last section, we used the semicolon to separate two different commands on the same line. That is one of its uses, but unlike many programming languages, a semicolon is NOT required at the end of every line. In fact, putting one on each line could be an error. To figure out what a semicolon does, try this:

>> ans
>> ans;


Note that the first command returned the value stored in ans. However, the second one did not. So, it looks like the semicolon suppresses output. In other words, MATLAB executed the command, but MATLAB did not display the results to the screen.

Every statement in MATLAB returns a value. If you type:

>> MyAge = 21


This assigns the value 21 to the variable MyAge. You will notice that it immediately returned

MyAge =
       21


However, you already knew that. If you write a script that makes thirty variable assignments and each one returns a line like that, your screen would have so much text that you wouldn't be able to read it all. Therefore, you would use a semicolon at the end of most assignment lines in a script to prevent all that output.

Matrices

Much of the work done with matrices can be fairly tedious. However, you can solve many mathematical problems using a matrix. That's where MATLAB comes in (remember what MATLAB stands for? --MATLAB is to Matricies what LISP is to Lists).

First, we should look at how to enter a matrix:

>> a=[10,34,59,89;23,83,58,34;43,43,32,40;3,83,77,17]


You get:

a =
   10 34 59 89
   23 83 58 34
   43 43 32 40
    3 83 77 17


Notice how you separate each entry by a comma. You separate each row by a semi-colon. For another example, you should define B as follows:

>> b=[1,3,5,7;2,4,6,8;10,20,30,40;8,37,14,2]


you get:

b =
    1  3  5  7
    2  4  6  8
   10 20 30 40
    8 37 14  2


Now we can do some math with the matrices. First, let's multiply them together. Type:

>> a * b


you get:

ans =
    1380 4639 3270 2880
    1041 2819 2829 3213
     769 2421 1993 2005
    1075 2510 3061 3799


Remember that matrix multiplication is not simply each term multiplied by its corresponding term in the other matrix. The rules are as follows:

  1. Given the two matrices, Matrix 1 and Matrix 2, whose values are:

    Matrix1 = [ a1 b1 ]
              [ a2 b2 ]

    Matrix2 = [ c1 d1 ]
              [ c2 d2 ]


  2. Matrix1 X Matrix2 is done like this:

    [ (a1*a2 + b1*c2) (a1*b2 + b1*d2) ]
    [ (c1*a2 + d1*c2) (c1*b2 + d1*d2) ]


If you aren't quite comfortable with this idea yet... you'll see it(a lot) more in Calc 2. Now, on the other hand, if you just want entry-times-entry multiplication, then you use:

>> a .* b


and get:

ans =
     10  102  295  623
     46  332  348  272
    430  860  960 1600
     24 3071 1078   34


The dot tells MATLAB to do straight, scalar multiplication on each entry.

Next, let's add them:

>> a + b


you get:

ans =
    11  37 64 96
    25  87 64 42
    53  63 62 80
    11 120 91 19


That was straightforward. MATLAB just adds each entry to its corresponding entry in the other matrix.

Finally, let's calculate the inverse of the matrix. MATLAB has a predefined function to do that:

>> inv(a)


returns:

ans =
    -0.0092 -0.0302  0.0406  0.0129
    -0.0038  0.0543 -0.0263 -0.0271
     0.0016 -0.0627  0.0299  0.0466
     0.0126  0.0242 -0.0144 -0.0220


Graphing and Plotting

MATLAB has the ability to plot data. Let us look at one example.

In this experiment, the distance a remote-controlled car traveled on a hill was recorded. The experiment was repeated 10 times. The following data was recorded.

Experiment 1

Trial

Distance (ft)

1

58.5

2

63.8

3

64.2

4

67.3

5

71.5

6

88.3

7

90.1

8

90.6

9

89.5

10

90.4

First, we must put each set of data into an array (or matrix with one row). We can do that as follows:

>> Trial = [1,2,3,4,5,6,7,8,9,10];
>> Distance = [58.5,63.8,64.2,67.3,71.5,88.3,90.1,90.6,89.5,90.4];


Now to plot it, simply type:

>> plot(Trial, Distance);


If you want a nicely labeled graph, try:

>> plot(Trial, Distance), title('Laboratory Experiment 1'),...
  xlabel('Trial'), ylabel('Distance, ft'),grid;


Here is what MATLAB will graph for you: [Graph 1]. This is the first time that we have come across a '...' This is called an ellipsis. In MATLAB, this just means that the statement is carried over on the next line (i.e. you use it if a line is too long to fit on a single line, this is especially nice when used in writing functions/scripts for MATLAB).

Experiment 2

Trial

Energy (J)

1

12

2

11

3

45

4

4

5

0

6

12

7

10

If you want to graph two lines on the same graph, you'll do something like this:

>> Trial_2 = 1:7;
>> Energy_2 = [12, 11, 45, 4, 0, 12, 10];
>> plot(Trial, Distance, Trial_2, Energy_2);


As you can see we did an unusual thing in making our first vector. We used the colon operator, the basic form is "x:y" which creates an array of numbers from x to y at 1-unit intervals (to find out how to do more interesting things with the colon operator do "help colon" in MATLAB). (Note that in MATLAB you can not use a dash '-' in your variable (or function) names; this is because MATLAB interprets any dashes as minus signs.)

Here is what MATLAB will graph for you: [Graph 2], notice how the data is plotted on the same graph. Since the graphs we just plotted are measuring totally different things, there is no reason to plot them on the same graph. To solve this, let's make two separate graphs in the same graph window, like this:

>> subplot(2,1,1),...
  plot(Trial, Distance),...
  title('Laboratory Experiment 1'),...
  xlabel('Trial'),...
  ylabel('Distance, ft'),...
  grid;

>> subplot(2,1,2),...
  plot(Trial_2, Energy_2),...
  title('Laboratory Experiment 2'),...
  xlabel('Trial'),...
  ylabel('Energy, J'),...
  grid;


Here is what MATLAB will graph for you: [Graph 3] There are many ways to alter the look of your plot. You can always look up information on functions by typing:

>> help <function name>



MATLAB Scripting & Functions

Setting the path

Before creating any new functions in MATLAB, you must first set the path so that MATLAB knows where to find your new files. The path is the listing of directories that MATLAB looks in to find program files. You can set the path with the following command in Windows (for other OS's syntax check out 'help path'):

>> path(path, 'c:\temp');


This tells MATLAB to set the path equal to the old path (which initially is set to the directories where the built-in functions are stored) plus the new directory, in single quotes. Of course, you can use something other than "c:\temp" if you want, but make sure that whatever directory you choose is where you put your script & function files (often called ".m files").

Writing Scripts

Let's say you wanted to put together a whole set of commands that you want MATLAB to run that are easy to edit and re-call; to do this you could write a MATLAB script. Start by making a file named:

<script name>.m


You can then write your script in your favorite text editor (Scripts must be written in plain-ASCII by such applications as pico, Notepad, Emacs or MATLAB's built-in scriptwriter).

Simply type in the commands you want to use into the file like so:

% my_script.m
Mass = 1:1:4
Acceleration = [3.2,9.6,2.8,1.23]
Force = Mass .* Acceleration


Then to run the script, just type the following in MATLAB:

>> my_script


MATLAB will then read through the script and treat each line as if it was individually entered at the command prompt. This is nice, but what we really love to do is to make functions, which MATLAB also loves... YEA!!!

Writing Functions

You can add new functionality to MATLAB by creating new functions. To do this, you first must write the function and then place it in a file called:

<function name>.m


...in the working directory you specified when setting the path. Functions should be written in ASCII by such applications as pico, Notepad, Emacs (or MATLAB's built-in scriptwriter).

Let us go through the process of creating a simple function using a function that we have used in Scheme --quadratic. Call it MyQuad. As you know, the function calculates the roots of a polynomial. You remember the formula:

Here is how the function would look:

function [Root1, Root2] = MyQuad(A,B,C)
% MyQuad Calculates the 2 roots of a quadratic,
% given A, B and C.
%

Bottom = (2*A);
Quotient = sqrt((B^2) - (4*A*C));
Root1 = (-1*B + Quotient) / Bottom
Root2 = (-1*B - Quotient) / Bottom


Create a text file containing the above data and save it as MyQuad.m (you should know how to do these things by now). Before figuring out what the script does line by line, try it out and make sure it works. To do this, go back to the evaluation window and type:

>> MyQuad(1,8,15);


(If the path is set correctly, this is all you have to type to run the function. You do not specifically "load" the file like Dr. Scheme.)

If you did everything correctly, Root1 will be -3 and Root2 will be -5.

Now, let us examine the code line by line:


In you don't already know, most of us around here (the staff of CS1321), get most of our health information from the back of cereal boxes. Recently a box of Raisin Bran gave us a special formula to determine if a person is overweight. The formula is:


INDEX = (704 * <your weight in pounds>) / (<your height in inches> ^ 2)


According to the cereal box (you should check the validity of this for yourself, remember we got it from a cereal box), if the value of INDEX is 25 or less, you're in great shape. If the value of INDEX is 30 or more, you're at significant risk for heart disease and other weight-related problems, that can only be solved by eating lots of cereal (we are beginning to suspect this is a subliminal advertisement).

An example for a 150 pound, 6 ft. tall person would be:

>> overweight_index(150, 72)


Now, write the Index function to figure out a person's overweight_index. However we'd like to do more than just compute the person's index, we'd like to print out a helpful message too, like this:

function index = overweight_index(weight, height)
% <Insert helpful comments here>
%

index = (704 * weight) / (height^2);

switch 1
  case (index <= 25)
    disp('You are in great shape');
  case (index >= 30)
    disp('You are at risk');
  otherwise
    disp('You are in the middle.');
end


What you probably notice is a thing called "switch", when used like this, "switch" works similar to the "cond" in Scheme, except that: Also like Scheme, you can combine using tests using "and" and "or" (look them up using "help" for more info).


...Recursion Recursion Recursion Recursion Recursion...

Recursion is very easy in MATLAB. All you have to do is call your function somewhere in your script. You just 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 "EAT MOR CHICKIN" x times.

switch 1
  case (x > 0)
    disp('EAT MOR CHICKIN');
    example(x-1);
  case (x == 0) % Notice that MATLAB uses == to test equality.
    disp('EAT MOR CHICKIN is a trademark of Chic-Fil-A');
end


For this function to run, save it in a file called "example.m" (remember the script name must be the same as the function's name + .m). As for the function 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 then makes a proper recursive call.


Your Quest

General

For each problem below, you will need to download the appropriate .m file (note: you may have to right-click on the link and select "save destination as"):

  1. lab4_script.m
  2. fact.m
  3. fibonacci.m
  4. rotation.m
The basic files have been setup for you, so use them. Notice that the familiar "student info" block is at top, please fill it in as you would on the HW's. When you are done with the problems it is suggested that you check out the "Check Your Answers" page.

Please note that a recursive solution is required for problems 2 and 3. Only recursive functions will be accepted for problems 2 and 3.



Problem 1: lab4_script.m

Download the file lab4_script.m and fill in the "missing parts". Here you will demonstrate some matrix and graphing tools. Then you will be asked to plot experimental data regarding a swallow (the data is given in the file).



Problem 2: fact.m

In order to cross the Bridge of Death each person answer five, um, sorry, three questions. One of them involves factorial. Write a recursive function to compute the factorial of a number. (Note: The Scheme version of this function appears in Section 11.4 of HtDP, please refer back there if you have forgotten the algorithm for factorial.)

Reminder: You Must use recursion for this problem. Use of MATLAB's "factorial" function is prohibited in solving this problem.



Problem 3: fibonacci.m

Roger the Schrubber has been asked to make an unusual schrubbery arrangement for the Knights who Say Ni. Each additional shrubbery must be taller then the schrubbery before it. To be specific the height must follow the fibonacci sequence.

Help Roger by writing a function fibonacci which takes in an integer and returns that term of the fibonacci sequence. (Note: The Scheme version of this function was coded in recitation during the week of 10/8, if you have forgotten the algorithm necessary, please refer back to your notes.)

Reminder: You Must use recursion for this problem.



Problem 4: rotation.m

When danger reared its ugly head,
He bravely turned his tail and fled
Yes Brave Sir Robin turned about
And gallantly he chickened out...
(Monty Python & The Holy Grail)

To help Brave Sir Robbin turn about quick enough to "chicken out" at the sight of danger, write a function that will create a transformation matrix for a rotation as defined by this mathematical function:

f(theta) = [ cos(theta) -sin(theta) ]
           [ sin(theta)  cos(theta) ]


Note that your function will take in a measure in radians (since this is the default angle measure in MATLAB) and create the associated matrix. You will then be able to apply this function as follows (note "pi" is a built-in constant in MATLAB):

>> [1 0] * rotation(pi/4);


MATLAB will return:

ans =
    0.7071 -0.7071




Turnin


Last modified: Tue Nov 6 01:54:23 EST 2001