|
MATLAB Tutorial
MATLAB is a powerful matrix based mathematics program. This tutorial
will give you an overview to basic Matlab commands and will help
you learn how more advanced features work. Use the following tutorial
as a basis for learning the vast capabilities of Matlab.
Table
of Contents:
Start
1)
Open X-Win 32 and set your display as described in the X-Win 32 Tutorial.
2)
Open an xterm window by typing xterm &.
3)
Type matlab at your UNIX prompt in the xterm window.
4)
Enter iamastudent for the password.
5)
Matlab is a matrix-based language that is extremely powerful for
managing and manipulating data. The two primary ways to input data are
by directly entering the matrices into Matlab or by loading data files.
Usually data files are a much more manageable way to handle your data
and should be used whenever possible.
For this tutorial go through your original telnet window and open Xemacs
or Pico by typing xemacs & or pico & at your prompt.
Create a file called Cardata that looks like this, with spaces
or tabs separating the two columns. Note that Xemacs cannot handle tabs.
| Position (cm) |
Time (s) |
| 5 |
1.2 |
| 10 |
2.3 |
| 15 |
4.6 |
| 20 |
5.2 |
| 25 |
7.8 |
| 30 |
8.8 |
| 35 |
10.0 |
| 40 |
11.2 |
This simulates a car going over a path with a timer clocking the elapsed
time.
Save the data file to your acpub account. In Xemacs this can be done
by hitting File>Save or hitting the Save button on the options bar.
In Pico you must hit Ctrl-X and type "y" when prompted
to save the file. Then you can type the name of the file you want to save
it as.
6)
For Matlab to understand the data file, all information extraneous
to the data itself must be deleted from the data file. So go back into
Cardata in either pico or Xemacs again, delete the headers “Position (cm)”
and “Time (cm)”, and resave the file as Car. It’s always a good idea
to save your original data as well as the raw data.
2-D Plots
7)
Go back to your xterm window and type:
load Car
This will load your data file into a 2 X 8 matrix, 2 columns and 8
rows. At any time in Matlab you can type help “command” where
“command” is the instruction you want more information about. Matlab
is case sensitive so it is extremely important when referencing files
or entering commands to type the name exactly as listed.
8)
Now you will separate your matrix into two vectors, Position and
Time.
*After each line of code press Enter.*
Type:
Position = Car(:,1);
Time = Car(:,2);
These commands say take the first column of the matrix Car and put all
its elements into a vector called position. Then do the same thing with
the second column.
9)
Then type:
plot(Time, Position)
This generates a 2 dimensional line graph with Time on the x-axis and
Position on the y-axis. If you would rather have a scatter plot the syntax
can be changed to plot(Time, Position, ‘o’), where the o marks
each point and can be replaced with a number of other symbols. See the
section on Traces for more information on plotting
options.
Instead of producing a line or scatter plot for the two variables you
may type(with x and y denoting variable names):
bar(x,y) for a bar graph
hist(x,y) for a bar histogram
barh(x,y) for a horizontal bar graph
pie(x) for a pie chart
stem(x,y) for a stem and leaf plot
polar(theta, rho) for a polar plot
Feel free to explore these on your own.
10) To label
your graphs use the commands:
xlabel(‘Time(s)’)
ylabel(‘Position(cm)’)
title(‘Position vs. Time’)
To modify the size and scaling of the axes the syntax:
axis([xmin, xmax, ymin, ymax])
may be used.
Other commands to use with the plot
function:
clf – clears everything inside the graphic window
cla – leaves the axes while clearing all curves inside the window
hold – holds your current figure so more than one curve may be
drawn on it, typing it again toggles the function off
axis(‘on’), axis(‘off’) – toggles the axis on or off
grid(‘on’), grid(‘off’) – toggles the grid on or off
figure – brings up another graphing window
figure(x) makes window x the current figure
The graph should look like this:

Traces
You may choose three options for each graph: color, symbol, and line
style
The eight color codes include - blue, green, red, cyan, magenta, yellow,
and white.
The thirteen symbols include a point, circle, x-mark, plus, star, and
square, and diamond, pentagram, hexagram, and triangles that point in
four directions (^,>,v,<).
The four different line styles include solid, dotted, dashdot, and dashed.
Using latex style commands, you can include Greek letters, subscripts,
and superscripts.
The FontSize property allows you to change the size of your text.
Finally you can create a legend and text for you plot. To create a legend,
use the legend command along with text strings. To create text,
use the text command along with the position of the text, and the
string of text you wish to display. You may also use the gtext
command to insert text on your graph by clicking the mouse at the desired
point of insertion. However, the gtext command is not reversible,
so be extremely careful with your placement. The following example will
create graphs using some of the types of graph options mentioned. *After
each line of code, press Enter.*
1)
x=linspace(0,5,50);
y1=cos(2*pi*x).*exp(-x/2);
y2=sin(2*pi*x).*exp(-x/2);
y3=cos(2*pi*x+pi/4).*exp(-x/2);
plot(x,y1,'r-',x,y2,'>--',x,y3,'bs');
xlabel('\zeta (radians)','FontSize',24);
ylabel('\Theta (degrees)','FontSize',24);
title(Plot of Theta vs. Zeta');
legend('y1','y2','y3');
text(2,.5,'See the text','FontSize', 12);

3-D Plots
11) To add in
a third dimension to your plots create a matrix called velocity
by entering:
Velocity=[2,2;4,4;6,6;8,8;3,3;1,1;5,5;4,4]
Velocity is now a 2X8 matrix with each of the values being the height
of the Time and Position coordinates. This would be extremely useful
in the case of plotting the temperature of a 2-D object or other cases
where a third dimension is a function of the first two.
12) To add this
to the first plot type
mesh(Velocity)
Your axis labels from the 2-D graph will disappear and you will have
a new, color-coded graph. (You may also wish to type legend again
to toggle the legend off of the figure)
Another way to accomplish a 3-D meshed plot is by typing:
[x,y]=meshgrid(Time,Position)
z=x+y (or some other function of Time(x) and Position(y))
mesh(z)
Now take some time to explore the plot3, surf and bar3 commands
by typing help plot3, etc.
13) Labels and
titles can be added just as they were in the 2-D plot to produce a final
plot like this:

Printing
To print your graph type:
Print –deps filename.eps
This saves your graph to your acpub account with the name filename.ps.
You can then FTP this to a desktop computer and print and view it using
Ghostview. For help using FTP go to http://www.oit.duke.edu/docs/ftp/index.html
Calculations with Single Variables
Define a variable by setting it equal to a value.
r=2;
To clear a variable, type clear
Variables that do not need to be defined are:
| eps |
machine epsilon |
| pi |
pi |
| i, j |
unit imaginary |
| inf |
infinity |
| NaN |
not a number |
| date |
date |
| flops |
floating point operation count |
| nargin |
number of function input arguments |
| nargout |
number of function output arguments |
| sin( ) |
takes the sine of the number in parenthesis |
| cos( ) |
takes the cosine of the number in parenthesis |
| tan( ) |
takes the tangent of the number in parenthesis |
| arcsin( ) |
finds the arcsine of the number in parenthesis |
| arccos( ) |
finds the arcosine of the number in parenthesis |
| arctan( ) |
finds the arctangent of the number in parenthesis |
Arithmetic operators include:
| + |
addition |
| - |
minus |
| * |
multiply |
| / |
divide |
| \ |
inverse division |
*After each line of code, press Enter*
1)
r=2;
vol=(4/3)*pi*r^3;
vol
When performing an operation on a matrix or an array, place a period
(.) before the operator to signify that the operation should be performed
on all elements of the matrix.
Without a semicolon, the result is displayed after the calculation. The
semicolon is not necessary in entering this type of code, however it is
useful in conserving screen space.
If/Else Statements:
if statements should always be followed by an end command.
Common symbols:
| = |
equal to |
| ~= |
not equal to |
| > |
greater than |
| < |
less than |
| >= |
greater than or equal to |
| <= |
less than or equal to |
| & |
and |
| | |
or |
| elseif |
else if |
| else |
else |
*After each line of code, press Enter*
1)
a=6;
b=1;
if a>5 & b<2, d=22;
end
d
2)
x=2;
if x>3, y=2;
elseif x==3, y=4;
else y=1;
end
disp(value) displays the variable contents, where value is the
name.
3)
disp(pi)
pi=
3.14159
For and While Loops
for and while loops must also be followed by an end command
break is used to prematurely end a loop.
*After each line of code, press Enter*
1)
r=0;
while r<5
r=r+1;
vol=(4/3)*pi*r^3;
disp([r, vol])
end
2)
for r=1:5
for s=1:r
Vol=(4/3)*pi*(r^3-s^3);
disp ([r,Vol])
end
end
The colon in the for statements stands for until, so the first
loop will run while r is equal to 1, 2, 3, 4, and 5.
Input and Output
input (‘type input’) takes in data entered by the user and assigns
it to a variable.
1)
Frogs = input('How many frogs?')
6
Arrays
To make an array, use commas to separate numbers within a row, and semicolons
to separate rows.
1)
x= [ 0, 1, 2; 2, 3, 4; 4, 5,
6; 7, 7, 7]
Extra Functions
| sort |
reorders elements in ascending order |
| sum(x) |
finds the summation of the elements of vector, x. |
| max(x) |
finds the maximum of vector x. |
| min(x) |
finds the minimum of vector x |
| rand(n) |
picks a random number of size matrix n. |
Saving
If you wish to save all your variables so that you can come back and
work on the same data at a later date type:
save stuff
This saves your variables to a file called stuff.mat. You
can reload your entire variable set during your next work session by typing:
load stuff
If you would only like to load a few variables from your
variable set type:
load stuff Frogs x pi
This will only load the variables Frogs, x, and pi
from stuff.
If you would like to save just a variable, you can do it by typing the
save command followed by the name of the file the variable should be stored
in, followed by the variable.
t=2;
save only_t t
This will save the variable t in a file called only_t.mat.
To load this variable type:
load only_t
|