Original tutorial written by Keith Yerex

Setting up the matlab path

To add any directories to your matlab path, use the export command in your .bashrc file. For example:
export MATLABPATH=$MATLABPATH:/home/dsk35/cscrs/c306/matlabdirs

Getting Started

Some useful commands to get aquainted with:
help (or helpwin) The help command is like the man page in unix. Executing help will give you all the possible primary topics. You can use help topic(ie. help general) to get a listing of the help for the topic. If you know the name of a function that you wish to get help from, use help functioname. Try "help images" to obtain a list of functions in the image processing toolbox.
lookfor Looks for the provided string in the first like of the help files of every fill in the MATLABPATH. Useful if you know a partial name of a function.

The matlab environment is interactive:

Try entering 3+7 at the command line. You will notice that it displays the result. If you place a semicolon at the end of the line, then the result is not displayed 3+7;. You may want to assign a variable, so x=3+7; and not want to see the result immediately. Now to display the contents of x, you can either type x, or disp(x). For the above example when you typed 3+7; you did not get a result displayed, but matlab keeps this answer in a variable ans, which you can use in the next expression, etc. Keep in mind that ans gets reassigned every time you evaluate an expression without assigning it to a variable.

Matlab workspace

Matlab has a current workspace, which keeps track of all the variables that have been assigned. You can see what variables are currently assigned by issueing a whos command. This displays the type,name and size of all the current variables. You can issue a whos x to get information about x only. You can also clear the entire workspace, or delete a variable by calling clear or clear variablename.

You can also preserve the current workspace for later use, by using the save command. The save command will write a file called matlab.mat, while save myfile saves to myfile.mat. The previous calls save the entire workspace, to save the state of a variable(s) just call save xdata x(additional variables can be saved by placing leaving replacing x in the previous command to x1 x2 etc.) to save the variable x to the file xdata(.mat files can get very large when you are dealing with images). You can load these .mat files at a later time by using the load command, which has similar syntax to the save command.

clear;
whos;
a=1;
b=a*a+2;
s='string';
whos;
save removethisfile a b s
clear;
whos;
load removethisfile;
whos;

Vectors

The basis element of matlab is a matrix(hence MATrix LABratory), with the exceptions of vectors(nx1 or 1Xn matrix) and scalars(1x1 matrix). One thing to make note of is that matrices and vectors are indexed from 1 to n, not 0 to n-1 as in c/c++. To initialize a row vector, use the square brackes as below:
v=[1,2,3];
w=[3,2,1];
x=v+w;
In this case v,w and x are row vectors. Exchange the commas with semicolons(or newlines) and the vectors will all be column vectors. To access an element of a vector you use brackets, so x=w(1) ==> x=3;

Another way to initialize vectors is to use the colon notation. The colon notation is first:step:last,where x=2:1:5 implies that x=[2,3,4,5]. The step is optional, if it is not there the stepping is done in increments of 1. You can also use the colon notation to access some elements of an array, or all of them. v(2:3) is the list [2,3] or v(1:3) returns [1,2,3]. Note that although v and w are row vectors v(1:3) returns a row vector, but v(:) returns a column vector.

Use the colon notation to access only the odd elements of a vector. Only the even.

Matrices

Similar to the vectors matrices are indexed starting from 1. So to access element at the I-th row and J-th column from matrix A, you have A(i,j).

Matrix initialization is done by specifying each row separated by semicolons or spaces. So :

A=[1,2,3;4,5,6;7,8,9];
gives us the matrix:
1 2 3
4 5 6
7 8 9
To get an empty matrix of a given dimension use zeros(n1,n2,...nk) which will return an empty matrix with dimensions n1*n2*..*nk. Similarily "ones" returns a matrix with ones in every entry and "eye" is used for the identity matrix. The empty matrix is denoted []. Matrices can also be concatenated, so B = [A A] is valid.

You can assign an entire row using:

A(1,:)=[1,2,3];
or assign a column:
A(:,1)=[1,4,8];

To determine the size of an vector or matrix you can use size(A), which will return a row vector containing the dimensions of A. To determine the size of the nth dimension you can use size(A,n).

Generate a 3x3 matrix that has ones in the column 1, twos in column 2 and three's in column 3. Use this matrix to generate a matrix with ones in row 1, twos in row 2 and threes in row 3. Swap the first and third colums of the first matrix using the colon operator.

Operations

Multiplication         *
Tranpose               '
pointwise mult        .*
pointwise div         ./
inverse               inv
determinant           det
cross            cross product of 2 vectors
Linear Least Squares x=A\b (for the system Ax=b)
...

A = [1,2,3;4,5,6];
B = A+1;
C = B.*A; % point wise multiplication
A = rand(100,3);
b = [1:100]';
x = A\b; % linear least squares solution to Ax=b

Plotting and Figures

Matlab uses figures to display graphical information. A figure is basically a window, and if you would like to pop up a window, use figure. You can use figure to pop up several windows, if you give it a handle as an argument(ie, figure(1)). clf clears the current figure, and gcf gets the current figure.
The plot function can be used to plot data in a 2d format. The hold on/off can be used to plot different data to the same axis.

figure(1);
x=[1:10]
plot(x,x.*x,'r');
xlabel('x-label');
ylabel('y-label');
hold on
plot(x,x.*x.*x,'b');
title('x^2 in red, x^3 in blue');
hold off;
plot3 similar to plot

Plotting some surfaces

[x,y]=meshgrid(-1:0.2:1,-1:0.2:1);
z = power(x+y,2);
subplot(1,3,1);
mesh(x,y,z);

[x,y]=meshgrid(-1:0.2:1,-1:0.2:1);
z2= x+y;
subplot(1,3,2);
mesh(x,y,z2);

subplot(1,3,3);
mesh(x,y,sin(4*x)+cos(4*y))
Use plot to plot the function f(x)=sin(x) for values of x from -pi to pi. Use plot to plot the function f(x)=sin(x)+cos(x+pi/2) for values of x from -pi to pi. What does this plot look like? What do you think it should be?(hint look at the scale on the axis, and think about its relation to the global variable eps)

control flow

Many control flow expressions the same as c/c++/java

a==b
=b
<=
...
with the exception of:
not equal ~= 
logical and & (in c this is a bit and)
logical or | (in c this is a bit or)

You can use these operators on entire matrices or vectors, and there will be ones and zeros depending on the output of the operator.

A = [1,2,3];
B = [3,2,1];
A==B
B~=A
If you want to identify which elements of the result is set you can use the find function. So if A=[1,2,3] and B=[3,2,1] then A==B is [0,1,0]. Find([0,1,0]) will return 2, since the second element is not zero. In general find will return all the indexes of non-zero elements in the input argument(It is also possible to retrieve the the row and column indexes for non-zero elements)
if (condition)
statments...
elseif (condition2)
statments..
...
end

for index=first:step:last
   statments
end

while condition
   statments
end

Script m-files

Commands in a script are run as if they are typed at the keyboard, so any variables you have currently been using in your workspace can be used in the script. Also, any variables created in the script are available after the script has executed.

Function m-files

nargin is the variable that contains how many variables were sent to your function. nargout is variable that contains how many variables are awaiting to be bound from your function. Sample function

function [outputargs] = fname(inputargs)
% Comments that appear in help file when help fname is called
%
%
statements in the body...

Write a simple function computing the factorial of a given input.

Image Processing

imread is used to load an image from a file. The image that you read in can be displayed using both imshow or image. When an rgb image is read in, the third dimension is the color data, so im(:,:,1) is the red channel, im(:,:,2) is green, and im(:,:,3) is blue.
Note: images are usually stored in unsigned chars(bytes) which is a uint8 type in matlab. You can not perform many operations on these data types so you must convert (like a cast) into some other appropriate type(double, uint8, uint16, uint32, int16, int32)

im = imread('image.jpg');
imshow(im);       % or image(im);
im = im-im/2;     % should be an error, since image is probably uint8
im = double(im);  % convert to double
im = im+10;       % this is now ok
imshow(uint8(im));
There are some differences between image and imshow, please see the help files for more information. Most of the time you will find that these functions try to assume something about the image based on the type of image they are receiving. So if it is a double image it may expect the values to be only between 0 and 1, this is why converting to a more suitable data type may be necessary. The function imwrite is used to write images, but for the work you are doing this will probably be used far less than imread. rgb2gray can be used to convert color images to grayscale. ginput obtains points from a user mouse click and can be useful for selecting regions of an image. An image histogram can be obtained with ease in matlab using hist.
im=imread('image.jpg'); % show default image of a child
P=ginput(2);% waits for two button presses
hist(im(:),0:255) %note this change
Write a function that takes an image filename and displays the image, and waits for two mouse clicks. Crop the image to the region inbetween the two clicks and display the result.

Write a function that computes the rotation matrix for a given angle. Use this rotation matrix to transform some 2d points. Display the points and their transformations using plot.

Write a function that takes a rgb image and converts the image so that the red channel becomes the blue channel, and vice versa.

Write a function that rotates an image for a given angle theta.

Something that may be of interest

Using complex Numbers for 2d points. Assuming a point in 2d is represented as p=[x,y], we can use complex numbers to store and operate on this number.

  c = x+yi, where i=sqrt(-1);
 
We can also rotate using complex number and complex multiplication
   r = cos(theta) + sin(theta)*i;
 

caution

  • make sure you don't overwrite i and j as variables(possibly in a loop) and then try using i or j as sqrt(-1). I do not mean "never" use i and j as variable names, I am just saying be aware that if you do overwrite them and attempt to use them later as if they were sqrt(-1)


Additional information on text and file input/output, structures, cell arrays, improving matlab code, see the tutorial or the help files.

Some useful Matlab links
   Math Works ( documentation and examples)
   Matlab course
   Matlab tutorial
   Matlab primer