Matlab is a mathematical computer language useful for manipulating matrices. Over the years, Matlab has found ways to express many different mathematical problems in its matrix notation. So although it might seem that a matrix program can only be used for working with matrices, in fact you can plot, work with polynomials, and do lots of things. An example of Matlab's use of matrices is the fact that even a number, for example "31", is stored by Matlab as a 1x1 matrix, and a vector is a "1xn" or "nx1" matrix, with n being the number of elements in the given vector. You can, of course, just use it as a calculator, typing in the matrices over and over, but when you start dealing with the larger matrices, this becomes tedious. Matlab allows you to assign the matrices (including single numbers) to variables, and then manipulate the variables instead of the matrices themselves.
Variables let you "store" a matrix as a single "name". It is important to note that variable names used in Matlab are case sensitive; if you want to call a matrix "items", for example, note that ITEMS, items, IteMs, iteMs, etc., are all different variable names. Also, variable names must start with a letter, followed by any letters, digits, or underscores. Variable names can contain up to 31 characters (a single character is a letter, number, etc., for example, the letter "a" is a character). Punctuation characters (e.g., a period ".") are not allowed, since many of them have special meaning in Matlab.
Note that it is customary to use upper case letters for matrices,
and lower case letters for vectors.
Open the Editor Window. You can do this by clicking on the
icon showing a blank page, or by opening the "file" menu and selecting
"new" and then "m-file".
Immediately type a comment line such as " % Jan 01, 2001". Notice
the symbol " % " that starts the line. This must always be present whatever
else you type.
Now select save and give your file a name. Let us suppose it is
called "Today". You are now ready to start working with Matlab.
Working with Matlab and the editor: You work with Matlab by
going through 5 steps.
1. Type commands into your file using the editor.
2. Save the new version of the file to disk.
3. Switch to the command window. (If you are in full-screen mode
then use the entries on the task bar.)
4. Type the name of the file to execute the commands in your file.
So in our example you type "Today", NOT "Today.m".
5. Look at the output that Matlab generates. After this you return
to step 1 by switching back to the editing window.
[1, 2, 3;4, 5, 6;7, 8, 9] (type it, save the file, run the file)
generates the matrix
Try it.1 2 3
4 5 6
7 8 9
% I am assigning a value to the variable Aand you will get the output
A = [1, 2, 3;4, 5, 6;7, 8, 9]
A =
1 2
3
4 5
6
7 8
9
Now this matrix is matrix "A". Notice by the way, that the command is preceded by a comment line. Always try to add comment lines.
As an aside from the current material, you will have noted if you typed in the last two commands that you got some output printed by each line in your file. When matrices become very large, the printing can take a long time. To stop output from appearing, you can put a semicolon ";" at the end of your command line. For example,Try it.B=[0, 9, 8;6, 5, 4;1, 2, 3]; % .................. note the semicolon at the end
will still assign the matrix to the variable "B", but won't give the output. To test that the matrix has been assigned to "B", just type in "B" at the command prompt, and hit enter; you will then get an output
» B
B =
0 9 8
6 5 4
1 2 3
a=[1, 2, 3, 4]
and you will get
a =
1 2 3 4
To make the same vector a column vector, you would put a " ' " character at the end of the square bracket. The " ' " is a command telling Matlab to transpose a vector or a matrix. (i.e. it also works for matrices). For example,
b = [1, 2, 3, 4]' ......... note the single quote at the end
will produce
b =
1
2
3
4
(Note that if you typed in "a" above, you could have also just typed
in b=a' to get the same result; this command assigns the transpose
of the vector a to the variable b.)
An alternative would be to type
b = [1 ; 2 ; 3 ; 4 ] .............. Notice those are semi-colons between the numbers
The same will work for a matrix. For example,
C=[1, 3, 5;2, 4, 6]' (.... again the single quote at the end!)
will give a 3-by-2 matrix (as opposed to D=[1 3 5;2 4 6], which will give a 2-by-3 matrix).
Try them both.
It is important to note that if you assign a matrix to a variable,
that variable will continue to represent that matrix until you reassign
the variable or you use the clear command. (For example, if you
have been typing in the commands as you read, the matrix you assigned to
"A" earlier on is still assigned to "A"; you can test this by typing in
"A" and hitting enter, and you will get the last matrix you assigned to
"A". You reassign the variable by simply typing in a new matrix for "A";
for example A=[1, 3;5, 6].
For help on the clear command, try going to the command window
and typing » help clear.)
x=[1:3:20]
creates the row matrix x=[1,4,7,10,13,16,19]. Notice that the last
entry is not 20; it is the one obtained by stepping up from the starting
value of 1.
If the step value is omitted, it is assumed to be 1.
c=[1:5]
creates a row matrix [1,2,3,4,5]. If you type
x=[1.0:0.1:2.0]
this will give a row matrix with elements from 1 to 2, with a spacing
of 0.1 between each of the elements.
Try it.
Other uses of ranges of numbers are to specify submatrices (next
paragraph) and to specify "for loops".
x = linspace(0,pi,30)
This creates 30 data points starting at 0 and stopping at pi (Matlab's way of writing the familiar 3.141592653). For the definition of the linspace command, type in the command window » help linspace.
Parentheses also allow us to pick out elements in a matrix. These can be single elements or submatrices. Picking out submatrices of a matrix can be thought of as a type of function calling. Suppose the matrix A is defined by
A=[1,2,3;4,5,6;7,8,9].
The matrix element A(2,3) is 6. The command A(2:3,1:2) picks out the submatrix [4,5;7,8]. If
B=[0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
then B(2:3:20) is the matrix [1,4,7,0,3,6,9]
>>fplot('humps',[0,2] )
The file 'humps' is already in Matlab m-files. Try entering help
humps. There are other built-in m-files as well. You can look them
up by using the command help. (More on m-files later.)
Frequently used matrix operations
+ AdditionWhen there is a dot, " . ", in front of the operation, such as " .* ", Matlab will multiply the corresponding elements (entries) of two matrices or vectors, as opposed to normal matrix multiplication (something you will already know or should be learning soon in class). For example,
- Subtraction
* Multiplication
^ Power
' Conjugate transpose
\ Left division
/ Right division
C = [1, 3;4, 6]*[4, 1;9, 3]
will give the result
C =
31 10whereas70 22
C = [1, 3;4, 6].*[4, 1;9, 3] (... note the "dot - star" between brackets)
will give the result
C =
4 3i.e. the " .* " command took the first row/first column element of the first matrix, multiplied it by the first row/first column element of the second matrix, and assigned the result to the first row/first column element of the new matrix "C", etc..)36 18
Try the following commands in your working file:
A=[1, 2, 3;4, 5, 6;7, 8, 0]
then
b=[366;804;351]
You will see displayed a 3-by-3 matrix A and a 3-by-1 matrix b. To find the determinant of matrix A, enter
det(A)
You will find that the determinant is different from zero. (It's 27). (Note we could have typed in d=det(A) to assign the answer of the determinant of A to the variable d, for example.)
To find the solution of the equation A*x = b, type in
x=A\b
This will give you the solution of x immediately.
x=[1,2,3,4]
y=[1,2,4,8]
z=x*y
You will get an error when Matlab reaches the last line.
Now change the file so that is reads
x=[1,2,3,4]
y=[1,2,4,8]
z=x .* y
% Notice the presence of the " . "
Now you get the answer z = [1,4,12,32]
In the same way,
z = x / y
gives the surprising output z= 0.5765
but
z = x ./ y
gives the result z = [1, 1, 0.75, 0.5 ]
Another example is the function ^, meaning "raise to a power".
[1,2;-4,5]^2
gives the answer [-7,12; -24,17], but
[1,2;-4,5] .^2
gives the answer [1,4;16,25]
The reason is that Matlab hides all the digits in x from you. To see
all the digits, you must type
format long
Then you will see that the statement
x=1/3
produces
x=
0.333333333333333
Remember that those extra digits are always present, whatever you see
on the screen.
To know more about the terms and functions used in Matlab, you can use the help command. In these brief notes, we will often omit explaining an unfamiliar word. Use help rand, for example, to find out about the term "rand".
Sometimes, the explanations can be very long. You may have to click the left mouse button on the screen border (at your right hand side) to scroll up and down, or simply use the "Page Up" and "Page Down" buttons on the keyboard, located above the arrow keys.
A list of definitions and explanations of that function will appear on the screen. Try (for example) the help rand command. Other frequently used functions in matrices are "zeros", "inv", "triu", etc..
There are example on matrices in Matlab. On the Matlab command window,
go to Help (located on the bar at the top of the Matlab command
window). Then select Examples and Demos. On the Matlab Demo Window,
choose the topic you want to see a list of demos for. Matlab will then
show you how to set up a matrix or other functions relating to matrices
step by step. Try it.
The next two items describe simple PROGRAMMING and PLOTTING. These are powerful features of Matlab - you should start trying them immediately.
Early in the course you will be writing simple programs - just lists of instructions written in the Editor/Debugger window - and saving them as "m-files" on a doskette disk or your Panther (Julian) hard drive. Later, by simply typing the name of the m-file into the Matlab command window you cause the sequence of commands to be followed. You can rerun the program over and over with different data without retyping it. This is a huge saving in effort for any but the simplest sets of calculations and you'll find yourself using it all the time.
After looking at a programming example, we give an example of curve plotting. Plotting curves turns out to be very convenient in Matlab as the example below shows so Matlab gives you a handy way to visualize the results of your calculations.
One other thing to mention here: You'll soon find yourself using Matlab in other courses and you'll wonder how you could ever get along without such a handy facility - especially the programming and plotting! And now here is a brief description of these two topics to get you started. Give them a try.
Saving your work by Writing M-files
An "m-file" is simply a file such as the one you have already created. Matlab knows how to interpret it. There are 2 kinds of m-files:
In the editor window (and even in the command window), all text after a percent sign (%) is taken as a comment statement; Matlab will not try to interpret anything on a line after a percent sign as a command. For example,
Erasers = 4 %Number of erasers
Matlab will simply ignore the percent sign and any text following it.
Multiple commands can be place on one line if commas or semicolons separate them.
After you finish writing the m-file, you must save it. It is possible to save it somewhere different from the default directory, and then you must add a path to the program in order for Matlab to run it.
To save your file to a floppy or on your Panther hard drive which is usually handier.
To run a file that you have saved to a floppy or h: drive:
- Saving to Floppy, a:
- Choose Save as… from the Editor/Debugger File menu.
- Insert a diskette into the A drive. Then from the "Save in" row at the top of the Save as window, select "3½ Floppy (A:)". You may have to backtrack to reach this choice.
- Type in the file name you want in the "File name" row at the bottom of this window, and in the "Save as type" row, make sure it says "Matlab (*.m)" (it may say other things there also, the *.m is the important one for us). Then click "Save".
- Saving the your Panther (Julian) hard drive, h:
- To use your own Hard Drive on Panther(Julian), you first double click on the icon called Map Home Directory which is near the Matlab icon in the Novell Accessory Screen. Then type in your Julian password and close this window. Then tell Matlab to use your hard drive by changing the default directory to h: using the command cd 'h:' and now any Matlab file in the editor/debugger window can be saved on your hard drive. For example, you can just click on File in the upper right corner of the editor window, choose Save As and then choose the h: drive and your preferred file name with the .m extension as usual.
Make the drive with the program the default directory:
» cd h:
Now you can run your m-file. If your file was called "prog.m" for example, just type in "prog". You will get an error message if you type "prog.m"
Make sure that the file name you use is not the same as the built-in files in Matlab or else you will have to specify which drive you are referring to; e.g. you will have to type A:prog or h:prog.
Here is a sample m-file you can try. Just open the Editor/Debugger window as explained above, and type in the following lines:
% Sample m-file
clear % This statement should start your m-file programs, assuming that you do not want to re-use variables already defined.
% "clear" ensures that your program uses only the variables you define in the program.
A=[3 4 5;2 2 1;4 5 3];Then save the file as "test" (remembering to save as type "*.m") to your 3.5" disk or hard drive(i.e. remember at the top of the Save as window, select "3½ Floppy (A:)" or "h:").B=ones(3); %Creates a 3x3 matrix with all elements = 1
C=[2 1 0;3 4 1;4 9 8];
X=A*B % Notice that this is the first line that will cause printing in your output
Y=A*C
Z=A.*C % Notice the " . " and notice that Y and Z are different%End of sample.
Next, go back to the Matlab command window, type in
» test
(remembering that before you did any of this, you must set the directory
to the one you are using. You can always see the files in your directory
by typing " dir"
Matlab will read in the file and execute the commands.
Example: As before open the edit window, type the opening comment and then type
close all % ......................This closes any plot windows you have already createdRun this file to see a graph of the sine function between 0 and 2¶ ( i.e. 6.28 ...)
x=linspace(0 , 2*pi , 30);
y=sin(x);
plot(x,y)
You can also plot 2 lines or more in one figure. Let's try to plot a sine and cosine on the same plot. ADD these lines to be file just created.
z=cos(x);
plot(x,y,x,z)
This time, sin(x) vs. x and cos(x) vs. x were plotted on the same plot. You can customize your plot by choosing the colour, marker, and line style for the lines. To specify a different colour for the markers, plot the same data with a different specification string, for example;
plot(x,y,'b:p',x,z,'m+')
Try it. (Note that the order of the " ' " and " , " is very important in the above command, and may be a bit difficult to see in this document).
To get a table of colours, markers and line styles that can be used in Matlab, type help plot.
You can also label your graph. Continuing with the example we were using, to label it, simply type (for example)
xlabel('independent Variable
X')
ylabel('Dependent Variable
Y and Z')
title('Sine and Cosine
Curves')
Be careful to notice something a little odd about Matlab. These last
3 statements come AFTER the plot command, not before it.
When graphing, sometimes the "Figure" window will not appear. That
is because the "Figure" window is already open and is stored at the bottom
of the screen, where the start button is located. Simply click on the figure
window you would like to open and the graph you want should appear.
Most programming in Matlab takes place in the context of functions. Therefore we should start by seeing how to write a function file in Matlab.
We shall suppose that you want to write a function called "FirstFunction".
To be specific, let us suppose you want to write a function to evaluate
the function
f(x)=sin(x)/x
so that you can plot it, or do something else useful with it.
Step 1: If you have not already done so, open the Matlab editor (or
equivalent).
Step 2: Let us assume you have already started typing in a script file
into the editor. Open a new window and start typing a new file.
Step 3. Your new file starts with the key word "function". It is this
word that tells Matlab to expect a function file not a script file.
Step 4. The output from your function will be returned to the calling
program through a variable. This variable is different from the name of
the function.
Let us call this variable "result". You have to tell Matlab two things:
the name of the function is "FirstFunction" and the name of the returning
variable is "result".
This is done by writing the first line as
function result=FirstFunction(x)
Step 5. Save the file. When you click on the save icon in the Matlab
editor, you will see that the editor has taken the name "FirstFunction"
from your typing and now offers to save the file under the name "FirstFunction.m".
It is important to realise that the SAME NAME must appear in two places.
The name of your function must also be the name of the file it is in.
Step 6. Now start typing in the code that the function will execute.
Remember that whenever possible, a Matlab function should work for a vector
of values
as well as for one value. Therefore we type
function result=FirstFunction(x)
% This function evaluates sin(x)/x for a vector of values x.
result=sin(x) ./ x
Step 7. Save this function and then try using it by calling it from
a script file. For example, you can make a script file that looks like
this:
% Script file to test FirstFunction
y=FirstFunction(1)
y=FirstFunction( [1,2] )
y=FirstFunction(0)
When you run the script file, you will see that the last line generates
an error message. This is not surprising, because the function is dividing
by x, and x=0.
In order to avoid this error message, we must learn more about programming,
Here, we will look at some sequences of control statements. The sequences are simple examples of programs. First, we give a list of useful relations and then we demonstrate three very powerful sequences of control statements. You should type them and then figure out how each example works.
Relations
< Less thanFor, While and If statements
> Greater than
<= Less than or equal
>= Greater than or equal
== Equal
~= Not equal
& And
| Or
~ Not
In their basic forms, these control statements are like those in most computer languages. In the following, we give examples as you would type them into the Editor.
1. For
The "for" loops allow a group of commands to be repeated a fixed, predetermined number of times. For example, for the given n = 10, the statements
x=[ ]; %on your printout, this may look like a
box - it's really beginning/ending square brackets.
n=10;
for j=1:n % this means loop from 1 up to n (n
is set = 10 in previous line)
x=[x,j^2]
% Notice that this line is indented.
% The Matlab editor usually does this to help you see what is happening
end
will produce 10 vectors. Try it. Note that a matrix may be empty. Here we start with an empty matrix, [], and "stretch" it one element at a time, each time we go through the loop. You can scroll back to earlier screens to see the full output.
Naturally, "for" loops can be nested as desired. For example, (notice the indenting again.)
for n=1:5
for m = 5:-1:1
A(n,m)=n^2+m^2;
end
disp(n) % use help disp to
find out about this command
end
2. While
The general form of a "while" loop is
While relationThe statements will be repeatedly executed as long as the relation remains true. For example,Statementsend
num = 0;
Epsilon = 1;
while(1+Epsilon)>1
Epsilon = Epsilon/2;
num = num + 1
end
Here, "num" and "Epsilon" are just variable names. As long as
(1+Epsilon)>1 is true, the commands inside the while loop are evaluated.
Note that the relation (1+Epsilon) is altered in each loop, as Epsilon
becomes the"old" Epsilon divided by 2. You should always include within
the while loop an alteration like this to the relation, so that eventually,
the relation will eventually be proved false, and the while loop can end
(what you want), because if you don't, you will have set up an infinite
loop, which will not end on its own! (CTRL-c will stop Matlab running a
command, if you seem to be in this situation).
In the above example, do not abbreviate the variable Epsilon down to
eps, because that is a built-in Matlab variable. Oddly, the user is allowed
to overwrite its Matlab
value with a new value, but it does not sound like a good idea.
3. If
The general form of a simple "if" statement is
if relationsIn two-way branching, the elseif portion would be omitted. For example,statementselseifstatementselsestatementsend
Epsilon=1;
for num=1:1000
Epsilon=Epsilon/2;
if (1+Epsilon)<=1
Epsilon=Epsilon*2
break
end
end
will give a numerical value for Epsilon. To find the last value of "num", run the mfile and when it stops just type
>>num
you should get num=53.
You may wonder what these last two programs calculate.
Think through each one for the first few steps.
Also, remember to use "help break" (or help with any other command, including help help) if you need to.
Here's one more program you can play around with...
% STANDING WAVE MOVIE
clear
x=linspace(0,pi,100);
y=sin(x);
N=100 % This is the default value. It can be changed
or read as input
% Here we give an example of an input
statement
N=input('How many curves do you want plotted?
')
% The user's response
is to enter a number on the keyboard and return
del=1 % Again this is a default value
del=input('How long a pause, in seconds,
do you want between plots? ')
figure % This starts a new graph.
% hold % This would keep all
the curves on the same figure.
% It's a bit messy in this case so we made this line a comment
for t=1:N
yy=sin(t*2*pi/N)*y; % You can
remove the semicolon if you need to debug
plot(x,yy)
axis([0, pi, -1, 1]) % This
keeps the same axes for all plots. See what
% happens if you comment this line out.
pause(del)
end
Another tip: You can use your left mouse button to "select" the lines of this m-file and then with your browser editor you can "copy" the lines. Then you can "paste" the lines into your Matlab Editor/Debugger window and modify and/or save them. This is a great way to avoid typing!
Now let us return to the function FirstFunction, that was presented
above. We want to avoid the division by zero. In addition, we want to use
the fact that
the limit of the function as x goes to zero is 1. So we want FirstFunction(0)
to return 1. We can do this by using an if statement.
function result=FirstFunction(x)
% This function calculates sin(x)/x and takes care of
the special case x=0
if x = = 0
result=1;
else
result = sin(x) ./ x ;
end
If you test that version, the result will be better for FirstFunction(0).
However, there is still the problem of FirstFunction( [-1,0,1] ).
Since the function is receiving a vector of values of x, we must search
all values. This can be done using a for loop:
function result=FirstFunction(x)
% This function calculates sin(x)/x and takes care of
the special case x=0
for i=1:length(x)
if x (i) = = 0
result(i) = 1;
else
result(i) = sin(x(i)) ./ x(i) ; % Notice that now we are computing
value by value, we could use " /" here.
end
end
This function could be improved further; you might like to read the
help for the FIND function and work on better versions.