You should have preliminary knowledge of starting programs in either
Unix systems (i.e. SGI) or NTs. In particular, you need to know how to
use a web browser (e.g. Netscape or Internet Explorer) to open up
the tutorial page (e.g. this one http://www.me.umn.edu/courses/me3201/tutorial.html
). On SGI's you should know how to open up "shells" or "command windows",
and to use standard text editors like "vi", or "emacs".
http://www.itlabs.umn.edu
machine 1% mkdir me3201_hw0(do not type "%") in the shell meant for UNIX commands. Enter that directory by typing
machine 2% cd me3201_hw0in both UNIX shells.
Type
machine 3% matlabat the UNIX prompt in the shell meant for Matlab. You should see the following:
< M A T L A B (R) >
(c) Copyright 1984-98 The MathWorks, Inc.
All Rights Reserved
Version 5.2.1.1420
Apr 30 1998
----------------------------------------------------------
Your MATLAB license will expire in 29 days.
Please contact your system administrator or
The MathWorks to renew this license.
----------------------------------------------------------
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, type tour or visit www.mathworks.com.
Starting Matlab in NT can be achieved from the Programs menu (using
the mouse and the left key click). You will get a Matlab command window.
You should again see the following:
< M A T L A B (R) >
(c) Copyright 1984-98 The MathWorks, Inc.
All Rights Reserved
Version 5.2.1.1420
Apr 30 1998
----------------------------------------------------------
Your MATLAB license will expire in 29 days.
Please contact your system administrator or
The MathWorks to renew this license.
----------------------------------------------------------
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, type tour or visit www.mathworks.com.
Help on individual
topics can be obtained by typing the second word in the list. You
can again get help on the subtopics by typing
help [subtopic].
For example, to get help on Elementary math functions, type "help elfun"
>> help elfun
at the Matlab prompt. To get help on the sine function within this module type
>> help sin
Some demos are available in Matlab which you can invoke using demos, demo, tour etc. at the Matlab prompt.
Type
>> help ops
to find out what types of simple operations are available.
Students are encouraged to visit these web sites and get exposure to working with Matlab. You should go through the tutorial at the end of this document.
The tutorial site at
http://www.engin.umich.edu/group/ctm/
is particularly helpful. Students are strongly encouraged to go through the Matlab basics exercises in this tutorial. Notice that this tutorial is designed so that you can use cut-and-paste to copy the commands on the tutorial page to the Matlab command window to try different things out quickly. For this reason, open up the web page (using Netscape or IExplorer) at the same time when you are working on Matlab.
>> more on
>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
This results in a 3x3 matrix which looks like
A =
1 2 3
4 5 6
7 8 9
There are many ways to generate a matrix. You may check the functions 'ones',
'zeros', and 'eye'. Other matrix generation functions
include 'rand', 'compan','hilb', and so on. At the end of this document
is a Matlab working tutorial which contains other examples.
and
>> B = [1, 2, 3; 4, 5, 6; 7, 8, 9],
Basically, ";" and "," are both terminators of statements. They differ
in that ";" supresses printing the answer whereas "," does not. Use the
help facility "help punct" to find out exactly what the differences are.
This generates a row vector [0, 2, 4, 6]. (Use "help punct" and "help colon" to learn exactly what it means).
>> dir
You should see the filename that you have saved your porgram in. If you do not see your file, you may not working in the same directory as the one you saved your file in, or vice versa. Suppose that you are saving your files in h:\jdoe\me3201_hw0, then you can use the
>> chdir h:\jdoe\me3201_hw0
to change directory. (Use "help chdir" to figure out how to use this
command.) Advanced users can use the "path" command to make sure that Matlab
searches a particular directory.
This lets you save your file in a postscript file named file_name.ps. Do not add an extension like .ps to the file name while using the print command. Postscript files are files that printers understand.
1.
Always start off your programs with the 'clear all' statement.
2. Develop a practice of using ample comments and always be sure to use
the '%' sign for writing comments. This ensures clarity in your programs
and tells the reader in plain English what is going on.
3. Maintain an uniform and consistent flow of thought when writing your
programs. Use an indented style . It makes the programs easier to read,
the program syntax is easier to check, and it forces you to think in terms
of building your programs in blocks.
4. Remember that many errors can be removed by simply checking the syntax
and ensuring that all variables which are being used are defined.
5.Remember to note error messages. Your programs will build on each
other. Error messages will help you debug future programs.
6.In Matlab, try to use built in functions rather than creating loops in
your programs. Matlab is optimized to run the built-in functions.
7.If you are having trouble writing a program, get a small part of it running
and try to build on that.
Acknowledgement. Most of this tutorial is taken from Rick Smith's Matlab Project Notes.
rand(7) rand(2,5) help randAnother special matrix is the Hilbert matrix:
hilb(5) help hilbA 5×5 magic square is given by
magic(5) help magicHere are some standard matrices from linear algebra:
eye(6) zeros(4,7) ones(5)You can build matrices several ways. Try
[1 2 3 5 7 9] [1, 2, 3; 4, 5, 6; 7, 8, 9] [1 2 (return) 3 4 (return) 5 6]Here (return) is the Return or Enter key. Try these:
[eye(2); zeros(2)] [eye(2); zeros(3)]Did you get an error message? Why? Now try
[eye(2), ones(2,3)]
a=magic(4) a'Notice that a' gave the transpose of a. Try these
3*a -a a+(-a) b=max(a) max(b)Some functions can return more than one value. The function max will return the maximum value and also the column index where the maximum occurs. Try
[m,i]=max(b) min(a) b=2*ones(a) a*b aUsually a dot in front of an operation will change the operation. In the case of multiplication a.*b will give entry-by-entry multiplication instead of the usual matrix multiplication. Try (dont forget the "dot"):
a.*b x=5 x^2 a*a a^2 a.^2 a triu(a) diag(a) diag(diag(a)) c=rand(4,5) size(c) [m,n]=size(c) m d=.5-cThere are many functions we apply to scales which can also be applied to matrices. Try
sin(d) exp(d) log(d) abs(d)MATLAB has functions to round floating point numbers to integers. The functions are round, fix, ceil, and floor. Try these
f=[-.5 .1 .5] round(f) fix(f) ceil(f) floor(f) sum(f) prod(f)
a=[1, 0, 1, 0] b=[1, 1, 0, 0] a==b a<=b ~a a&b a&~a a|b a|~aThe function any is used to determine whether there is a nonzero entry in a vector. The function all determines if all the entries are zero. Try
a any(a) all(a) c=zeros(1,4) d=ones(1,4) any(c) all(d) e=[a', b', c', d'] any(e) all(e) any(all(e))
x=-2:1 length(x) -2:.5:1 -2:.2:1 a=magic(5) a(2,3)Now we will use the colon notation to get a column of a.
a(2,:) a(:,3) a a(2:4,:) a(:,3:5) a(2:4,3:5) a(1:2:5,:)You can put a vector in the row or column position of a.
a(:,[1, 2, 5]) a([2, 5], [2, 4, 5])You can also make assignment statements using a vector or a matrix.
b=magic(5) b([1 2],:)=a([1 2],:) a(:,[1 2])=b(:,[3 5]) a(:,[1 5])=a(:,[5 1]) a=a(:,5:-1:1)When you insert a 0-1 vector into the column position, the columns which correspond to the 1's are displayed. Try
v=[0 1 0 1 1] a(:,v) a(v,:)
function r=mod(a,d) % r=mod(a,d). If a and d are integers, then r is the integer % remainder of a after division by d. If a and d are integer % matrices, then r is the matrix of remainders after division % by corresponding entries. Compare with MATLAB's rem. r=a-d.*floor(a./d)You should make a file named mod.m and enter this program exactly as it is written. Or you can download it. Now assign some integer values for a and d. Run
mod(a,d)This should run like any builtin MATLAB function. Type
help modThis should produce the comments that follow the % signs. Now type
type modThis will give a listing of the file.
if condition, program end
Here condition is a MATLAB function and program is a
program segment. The entire construction executes the i>program just in
case the value of condition is not 0. If that value is 0, the control
moves on to the next program construction. You should keep in mind that
MATLAB regards a==b and a<=b with values 0 or 1. Below
are two more variations.
if condition,
program1
else
program2
end
In this case, if condition is 0, then program2 is executed.
if condition1,
program1
elseif condition2
program2
end
This time if condtion1 is not 0, then program1 is executed.
If condition1 is 0 and if condition2 is not 0, then program2
is executed. Otherwise control is passed on to the next construction. Here
is a short program to illustrate branching.
function b=even(n) % b=even(n). If n is an even integer, % then b=1, otherwise b=0. if mod(n,2)==0, b=1; else b=0; end
for i=1:n, program, end
Here we will repeat program once for each index value i.
Below are some sample programs.
function c=add(a,b) % c=add(a,b). This is the function % which adds the matrices a and b. % It duplicates the MATLAB function % a+b. [m,n]=size(a); [k,l]=size(b); if m~=k | n~=l, error('matrices not the same size'); return, end c=zeros(m,n) for i=1:m, for j=1:n, c(i,j)=a(i,j)+b(i,j); end endThe next program is matrix multiplication.
function c=mult(a,b) % c=mult(a,b). This is the matrix product % of the matrices a and b. % It duplicates the MATLAB function % a*b. [m,n]=size(a); [k,l]=size(b); if n~=k, error('matrices are not compatible'); return, end c=zeros(m,l) for i=1:m, for j=1:n, for p=1:n, c(i,j)=a(i,j)+a(i,p)*b(p,j); end end endNotice how the branch construction was used for error messages.
while condition, program, end
Here condition is a MATLAB functionm, as with the branching construction. The program program will execute successively as long as the vlaue of condition is not 0. Here is a sample program.
function l=twolog(n) % l=twolog(n). l is the floor of % the base 2 logarithm of n. l=0; m=2; while m<=n l=l+1; m=2*m; end
function y=twoexp(n) % y=twoexp(n). This is a recursive program % for computing y=2^n. the program halts % only if n is a nonnegative integer. if n==0, y=1; else y=2*twoexp(n-1); end
if A~=B, program, end
You would like program to execute if the matrices A and B differ i some entry. Under the convention, program will only execute when they differ on all entries. There are some ways around this problem. One is the construction
if A==B, else program, end
which will pass control to the "else" part if A and B differ on at least one entry. Another solution is to convert A==B into a binary valued functionm by using all(all(A==B)). The inside all creates a binary vector whose i^{th} entry is 1 only if the i^{th} column of A is the same as the i^{th} column of B. The outside all produces a 1 if all the entries of the vector are 1. Thus if A and B differ on at least one entry, then all(all(A==B))=0. The construction
if ~all(all(A==B))), program, end
then behaves in the desired way.
A script is an m-file without a function declaration at the top.
A script treats variables differently than a function file. In a script,
if x appears in a program, which you might call scrpt,
and x has a value in your session, then a call to scrpt
might change the value of x. If you do not make that function
declaration, then the variables in your session can be altered. Sometimes
this is useful but usually it is recommended that you use function files.
magic | round | help | function | == |
eye | floor | format short | if | ~= |
diag | abs | format long | else | < |
ones | sqrt | who | elseif | <= |
zeros | sin | clear | end | > |
rand | cos | exit | while | >= |
hilb | tan | ans | return | & |
tril | asin | load | = | | |
triu | acos | save | ; | ~ |
sum | atan | diary | : | any |
prod | exp | type | % | all |
max | log | dir | , | + |
min | eps | - | ||
size | pi | * | ||
length | sign | . | ||
' | ||||
' | ||||
/ | ||||
./ | ||||
^ | ||||
.^ |