MATLAB TUTORIAL

Acknowledgement. Most of this tutorial is taken from Rick Smith's Matlab Project Notes.

You can download the entire tutorial as a text-file.




1. Building Matrices

Matlab has many types of matrices which are built into the system. Try

rand(7)
rand(2,5)
help rand

Another special matrix is the Hilbert matrix:

hilb(5)
help hilb

A 5×5 magic square is given by

magic(5)
help magic

Here 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)]






2. Functions

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(size(a))
a*b
a

Usually 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-c

There 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)






3. Relations and Logical Operations

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

The 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))






4. Colon Notation

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)

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,:)






5. Programming in Matlab

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.






5.1 Assignment

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)



Using a text editor you should create a file named mod.m and enter this program exactly as it is written. Or you can download it.

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)

This should run like any builtin MATLAB function. Type

help mod

This should produce the comments that follow the % signs. Now type

type mod

This will give a listing of the file.







5.2 Branching

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







5.3 For Loops

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.







5.4 While Loops

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







5.5 Recursion

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







5.6 Miscellaneous

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.






5.7 Scripts

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.






6. Key Words and Symbols

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.