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).
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.
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?
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
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.
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.
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:
Matrix1 = [ a1 b1 ]
[ a2 b2 ]
Matrix2 = [ c1 d1 ]
[ c2 d2 ]
[ (a1*a2 + b1*c2) (a1*b2 + b1*d2) ]
[ (c1*a2 + d1*c2) (c1*b2 + d1*d2) ]
>> a .* b
ans =
10 102 295 623
46 332 348 272
430 860 960 1600
24 3071 1078 34
>> a + b
ans =
11 37 64 96
25 87 64 42
53 63 62 80
11 120 91 19
>> inv(a)
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
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>
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');
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!!!
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:
>> [Root1,Root2]=MyQuad(1,8,15)
INDEX = (704 * <your weight in pounds>) / (<your height in inches> ^ 2)
>> overweight_index(150, 72)
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
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.
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"):
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.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).
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.
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.
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