Alex's MatLab Tutorial
Written by: Alexander Stoytchev
Last Updated: Aug 24, 2001.
INTRO
MatLab stands for Matrix Laboratory.
As the name suggests most of the operations have as input
or output a matrix or a vector.
MatLab is available for SGI and SUN machines on the CoC network. To run the
program type 'matlab'.
MatLab is an interpreted language. You can type commands at the MatLab prompt
or save the commands in a *.m file and load them by typing at the prompt just
the file name without the .m extension.
MATRIX AND VECTOR OPERATIONS
This is how we can define a vector
>> v=[1, 2, 3]
Matlab Prints out the following
v =
1 2 3
Similarly we can define a matrix
>> M= [ 1 2 3; 4 5 6; 7 8 9]
The result is:
M =
1 2 3
4 5 6
7 8 9
If you want to suppress the MatLab output then you need
to finish the line with semicolon ';'
M= [ 1 2 3; 4 5 6; 7 8 9];
To find the sum of the columns of M we can use the 'sum' function.
>> sum(M)
ans =
12 15 18
To fin the sum of all elements use
>> sum(sum(M))
ans =
45
Note that the 'sum' function takes both matrices and vectors as
parameters. The inner 'sum' takes a matrix and outputs a vector which is
the input for the outer 'sum'.
By default the output is assigned to the 'ans' variable unless we
assign the output explicitly
>> s=sum(M)
s =
12 15 18
>> result= s+v
result =
13 17 21
Some operations can produce long output. Typing 'more on'
will switch to paging mode similar to "| more" in UNIX.
'more off' reverts to normal output.
To transpose a vector or a matrix the operator is just '.
>> v'
ans =
1
2
3
>> M'
ans =
1 4 7
2 5 8
3 6 9
To perform a component-by-component operation on a vector or matrix
prepend the arithmetic operator by a '.'
>> M .* M
ans =
1 4 9
16 25 36
49 64 81
This squares each element of the matrix. The result is different from
squaring the matrix as shown below.
>> M*M
ans =
30 36 42
66 81 96
102 126 150
To get a subset of a matrix do the following
>> M11=M(2:3 , 2:3)
M11 =
5 6
8 9
To get all elements in a given dimension one can use ':'
>> A= M( :, 1:2)
A =
1 2
4 5
7 8
FUNCTIONS
Each function should be separated in a *.m file and should have the same name
as the file. The syntax for defining a function is:
function res= myfunction(A,b)
where A and b are parameters and res is the variable whose value
is returned as a result from the function. myfunction is an arbitrary
function name.
PLOTS
Let's write a function to calculate a simple polynomial.
(put the following two line in a file named mypoly.m)
function y=mypoly(x)
y= 3*(x.^2)+ 4*x + 5;
On the program prompt type
>> x= -4:0.05:4;
>> y=mypoly(x);
>> plot(x,y)
This will pop up a graphical window with the plot of y=3x^2 +4x +5
in the interval [-4; 4].
If for some reason we need to overlay two plots on the same graph
the command 'hold on' can be used to hold the current display and
show all subsequent plots on top of the first one. 'hold off' turns
that capability off.
3D PLOTS
Example: A helix:
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t);
3D SURFACES
x=1:10;
y=1:10;
Z=x'*y;
surf(x,y,Z);
% Some fancy stuff
xlabel('X');
ylabel('Y');
zlabel('Z');
title('My Plot');
Note that here Z is a matrix holding the z value for every combination
of x and y.
FLOW CONTROL
IF Example
a=2;
b=3;
if a >= b
c=a+b;
elseif a ~= b
c=2*a*b;
else
c= 5*b;
end
Note that 'not equal' is written ~= and not != as it is in C.
FOR Example
m=5;
n=5;
for i=1:m
for j=1:n
A(i,j)=i+j;
end
end
A
Break is also defined and has the same meaning as in C.
WHILE Example (bisection method for root finding)
a=0; fa= -Inf;
b=3; fb= Inf;
while b-a > eps*b
x= (a+b)/2;
fx= x^3 -2*x -5;
if fx == 0
break;
elseif sign(fx) == sign (fa)
a=x; fa = fx;
else
b = x; fb = fx;
end
end
x
If possible avoid using 'for' loops. Try to rewrite the computation in
matrix form. Because MatLab is interpreted 'for' loops take a lot of time.
For example:
x=0;
for i=1:31
y(i)= sin(x);
x=x+0.1;
end
Can be rewritten as:
x2=0:0.1:3;
y2=sin(x2);
CELL ARRAYS
Matrices and vectors can have only elements of the same type. They also
have fixed dimensions. To overcome this limitation cell arrays are introduced.
C= cell(3,2)
C{1,1}=[1,2];
C{1,2}=[3,4];
C{2,1}=[5 6;
7 8];
C{2,2}=[ 9 10 11;
12 13 14];
C{3,1}= ones(3);
C{3,2}='Hello';
To access an element type:
>> C{3,1}
ans =
1 1 1
1 1 1
1 1 1
>> C{2,2}(1,3)
ans =
11
Note the use of the two different kinds of parentheses. The first one '{}'
accesses the cell array elements. The second one '()' accesses the elements
of the object contained in the cell array.
WORKING WITH IMAGES
Basic functions:
img=imread('image1.jpg');
imwrite(img, 'image2.jpg');
Example: Inverting an image
IMG1=imread('face1.tiff');
%This does not work
%RES= 255 -IMG1;
%To add two images we need to convert to double and
% then rescale the result back so that it looks like an image
RES= 1 - double(IMG1)/255;
figure
imshow ( uint8(round(RES*255)) )
Conversions:
From uint8 to double
B= double(A)/255; % Intensity or RGB
B= double(A); % Binary
From double to unit8
B= uint8(round(A*255)); % Intensity or RGB
B= logical(uint8(round(A))); % Binary
PPM/PGM FUNCTIONS FOR MATLAB
imread_pgm.m
imwrite_pgm.m
imread_ppm.m
imwrite_ppm.m
test_ppm_pgm.m
(test matlab program)
mrl_logo.jpg
(test image)
IMAGE CROPPING EXAMPLE
image_crop.m
face1.tiff
WHERE TO GET HELP
On a MatLab prompt type: help
For example: help sum
Most command names are rather cryptic and easy to forget. You can look
for help using a keyword with the 'lookfor' command.
For example: lookfor eigenvalue
(this will produce a long list of command names and their descriptions all
of which have to do something with eigenvalues).
'helpdesk' is a Matlab command which brings up a web browser
with pointers to the documentation. The same can be achieved with the
links given below.
From a Unix machine on the CoC network Matlab documentation is available at:
file:/usr/local/matlab6/help/helpdesk.html
Use file://username@gaia.cc.gatech.edu/usr/local/matlab6/help/helpdesk.html
to get remote access to the matlab documentation. You need an account on
gaia so you can log in. Replace "username" with your account name.
Getting Started with MATLAB ( highly recommended!)
file:/usr/local/matlab6/help/pdf_doc/matlab/getstart.pdf
Online Manuals (in PDF)
file:/usr/local/matlab6/help/pdf_doc/matlab/
For general info about MatLab check out
http://www.mathworks.com/
Last Updated Aug 24, 2001.