Acknowledgement. Most of this tutorial is taken from Rick Smith's Matlab Project Notes.
You can download the entire tutorial as a text-file.
Matlab has many types of matrices which are built into the system. Try
rand(7) rand(2,5) help rand
hilb(5) help hilb
magic(5) help magic
eye(6) zeros(4,7) ones(5)
[1 2 3 5 7 9] [1, 2, 3; 4, 5, 6; 7, 8, 9] [1 2 (return) 3 4 (return) 5 6]
[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'
3*a -a a+(-a) b=max(a) max(b)
[m,i]=max(b) min(a) b=2*ones(size(a)) a*b a
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-c
sin(d) exp(d) log(d) abs(d)
f=[-.5 .1 .5] round(f) fix(f) ceil(f) floor(f) sum(f) prod(f)
In this section you should think of 1 as "true" and 0 as "false". The notations &, |, ~ stand for "and", "or" and "not", respectively. The notation == is a check for equality. Try these
a=[1, 0, 1, 0] b=[1, 1, 0, 0] a==b a<=b ~a a&b a&~a a|b a|~a
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))
MATLAB also offers some very powerful ways for creating vectors and then using this means to tear a matric apart. Try
x=-2:1 length(x) -2:.5:1 -2:.2:1 a=magic(5) a(2,3)
a(2,:) a(:,3) a a(2:4,:) a(:,3:5) a(2:4,3:5) a(1:2:5,:)
a(:,[1, 2, 5]) a([2, 5], [2, 4, 5])
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)
v=[0 1 0 1 1] a(:,v) a(v,:)
MATLAB is also a programming languange. By creating a file with the extension .m you can easily write and run programs. If you were to create a program file myfile.m in the MATLAB language, then you can call the command myfile from MATLAB and it will run like any other MATLAB function. If you are using a PC you will also need to set path if you are doing this for the first time, so that MATLAB can find your program. See note below. There is no need to compile the program since MATLAB is an interpretative language. Such a file is called a m-file. We will describe the basic programming constructions. These should be enough to enable you to write clear programs.
Assignment is the method of giving a value to a varaiable. You have already seen this in the interactive mode. We write x=a to give the value of a to x. Here is a short program illustrating the use of assignment.
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)
If you are using MATLAB on a PC you will need to set path so that MATLAB can find you program. To do this click on File in the menu bar and then click on set path. Next select the folder the contains your m-file and click save. Now you can call the function from within MATLAB.
Now assign some integer values for a and d. Run
mod(a,d)
help mod
type mod
Branching is the construction
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
A for loop is a construction of the form
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 end
The 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 end
Notice how the branch construction was used for error messages.
A while loop is a construction of the form
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
Recursion is a devious construction which allows a function to call itself. Here is a simple example:
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
It is possible to place a matrix valued function as the condition of a branching construction or while loop. However one must be careful! Consider the construction
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 ith entry is 1 only if the ith column of A is the same as the ith 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.
We have seen m-files which have the function declaration at the top. In practice these files create new MATLAB functions. In creating a function whcih we will call fun(a) we might use a variable like x. Now suppose that the variable x has a value in your session? What happens to the value x after you make a call to fun(a)? Nothing. The only way to change the value of x when running fun is to assign x=fun(a). The x inside the program fun.m behaves independently from the variable x in your session.
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 | . | ||
' | ||||
' | ||||
/ | ||||
./ | ||||
^ | ||||
.^ | ||||
Last update made Mon May 15 13:22:43 EDT 2017.