MATLAB TUTORIAL
YOUTUBE PLAYLIST LINK
Matlab Basics
Matrix Laboratory
Dynamically typed language
Variables require no declaration
Variable declaration can be done by initialization (a=5;)
All variables are treated as matrices
Simple number 1X1 matrix; vector NX1 or 1XN matrix
Advantages
Calculations are much faster
Implementation and debugging is easy
Very simple way and easy way to do matrix operation
Powerful image processing toolbox
MATLAB is a tool for technical computing, computation
and visualization in an integrated environment, e.g.,
• Math and computation
• Algorithm development
• Data acquisition
• Modeling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics
• Application development, including graphical user
interface building
Main window
Matlab as calculator
>> 2+2
Ans=
4
>> sqrt(3)
Ans=
1.732
>>exp(5)
Ans=
148.4132
You can suppress the results by putting a semicolon at
the end
>> exp(5);
>>
Variables in Matlab
To create a new variable, enter the variable name in the
Command Window, followed by an equal sign (=) and the value
you want to assign to the variable. For example, if you run these
statements, MATLAB adds the three variables x, A, and I to the
workspace:
>>x = 5.71;
>>A = [1 2 3; 4 5 6; 7 8 9];
>>I = besseli(2,5); % besseli(n,z) computes the modified Bessel
function of the first kind In(z) for each element in array z.
You do not have to declare the variables before assigning a
value, it will automatically get the type!!
Variable in Matlab
One can change the variable by double clicking the
workspace and change it in it..
Matlab’s Useful Commands
• help –Help
• help x –Gives you help on subject “x”
• who , whos – current workspace variables
• save – save workspace vars to *.mat file.
• load – load variables from *.mat file.
• clear all – clear workspace vars.
• close all – close all figures
• clc – clear screen
• clf – clear figure
Basic Commands
• % used to denote a comment
• ; suppresses display of value (when
placed at end of a statement)
• ...continues the statement on next line
• eps machine epsilon
• inf infinity
• NaN not-a number, e.g., 0/0.
Numbers
• To change format of numbers:
format long, format short, etc.
See “help format”.
• Mathematical functions: sqrt(x), exp(x),
cos(x), sin(x), sum(x), etc.
• Operations: + , -, *, /
• Constants: pi , exp(1), etc.
Arrays and Matrices
• v = [-2 3 0 4.5 -1.5]; % length 5 row vector.
• v = v’;% transposes v.
• v(1);% first element of v.
• v(2:4);% entries 2-4 of v.
• v([3,5]);% returns entries 3 & 5.
• MATLAB provides a simple way to define simple
arrays using the syntax: “init:increment:terminator”.
For instance:
• v=[4:-1:2];% same as v=[4 3 2];
• a=1:3; b=2:3; c=[a b]; c = [1 2 3 2 3];
Arrays and Matrices (2)
• x = linspace(-pi,pi,10); % creates 10 linearly-spaced
elements from –pi to pi.
• logspace is similar.
• []. Parentheses: () are used to access elements and
subarrays (they are also used to denote a function
argument list).
• A = [1 2 3; 4 5 6]; % creates 2x3 matrix
• A(1,2) % the element in row 1, column 2.
• A(:,2) % the second column.
• A(2,:) % the second row.
Note that the indexing is one-based, which is the usual
convention for matrices in mathematics. This is atypical for
programming languages, whose arrays more often start with
zero
Arrays and Matrices (3)
• A+B , A-B, 2*A, A*B% matrix addition,
matrix subtraction, scalar multiplication,
matrix multiplication
• A.*B% element-by-element mult.
• A’% transpose of A (complex-conjugate
transpose)
• det(A)% determinant of A
Creating special matrices
• diag(v)% change a vector v to a diagonal matrix.
• diag(A)% get diagonal of A.
• eye(n)% identity matrix of size n.
• zeros(m,n)% m-by-n zero matrix. >> eye(3)
• ones(m,n)% m*n matrix with all ones. ans =
100
010
001
>> zeros(2,3)
ans =
000
000
>> ones(2,3)
ans =
111
111
More matrix/vector operations
• length(v)% determine length of vector.
• size(A)% determine size of matrix.
• rank(A)% determine rank of matrix.
• norm(A), norm(A,1), norm(A,inf)
% determine 2-norm, 1-norm,
and infinity-norm of A.
•norm(v)% compute vector 2-norm.
Logical Conditions
• ==, < , > , <= , >= , ~= (not equal), ~ (not)
• & (element-wise logical and), | (or)
• find(‘condition’) – Return indices of A’s
elements that satisfies the condition.
Solving Linear Equations
• A = [1 2 3; 2 5 3; 1 0 8];
• b = [2; 1; 0];
• x = inv(A)*b; % solves Ax=b if A is invertible.
(Note: This is a BAD way to solve the
equations!!! It’s unstable and inefficient.)
• x = A\b; % solves Ax = b.
(Note: This way is better, but we’ll learn how to
program methods to solve Ax=b.)
Do NOT use either of these commands in your
codes!
For loops
• x = 0;
for i=1:2:5 % start at 1, increment by 2
x = x+i; % end with 5.
end;
This computes x = 0+1+3+5=9.
While loops
• x=7;
while (x > = 0)
x = x-2;
end;
This computes x = 7-2-2-2-2 = -1.
If statements
• if (x == 3)
disp(‘The value of x is 3.’);
elseif (x == 5)
disp(‘The value of x is 5.’);
else
disp(‘The value of x is not 3 or 5.’);
end;
Switch statement
• switch Case
case {1}
disp(‘Rolled a 1’);
case {2}
disp(‘Rolled a 2’);
otherwise
disp(‘Rolled a number >= 3’);
end;
Break statements
• break – terminates execution of for and
while loops. For nested loops, it exits in
the innermost loop only.
Vectorization
• Because Matlab is an interpreted
language, i.e., it is not compiled before
execution, loops run slowly.
• Vectorized code runs faster in Matlab.
• Example: x=[1 2 3];
for i=1:3 Vectorized:
x(i) = x(i)+5; VS. x = x+5;
end;
Graphics
• x = linspace(-1,1,10);
• y = sin(x);
• plot(x,y);% plots y vs. x.
• plot(x,y,’k-’); % plots a black line
of y vs. x.
• hold on;% put several plots in the same figure
window.
• figure;% open new figure window.
Graphics (2)
• plot3(x,y,z)% plot 2D function.
• mesh(x_ax,y_ax,z_mat) – surface plot.
• contour(z_mat) – contour plot of z.
• axis([xmin xmax ymin ymax]) – change
axes
• title(‘My title’); - add title to figure;
• xlabel, ylabel – label axes.
• legend – add key to figure.
Examples of Matlab Plots
Examples of Matlab Plots
Examples of Matlab Plots
File Input/Output
• fid = fopen(‘in.dat’,’rt’);% open text file
for reading.
• v = fscanf(fid,’%lg’,10); % read 10
doubles from the text file.
• fclose(fid);% close the file.
• help textread;% formatted read.
• help fprintf;% formatted write.
Example Data File
Sally Type1 12.34 45 Yes
Joe Type2 23.54 60 No
Bill Type1 34.90 12 No
Read Entire Dataset
fid = fopen(‘mydata.dat’, ‘r’); % open file
for reading.
% Read-in data from mydata.dat.
[names,types,x,y,answer] =
textread(fid,’%s%s%f%d%s’);
fclose(fid); % close file.
Read Partial Dataset
fid = fopen(‘mydata.dat’, ‘r’); % open file
for reading.
% Read-in first column of data from mydata.dat.
[names] = textread(fid,’%s %*s %*f %*d %*s’);
fclose(fid); % close file.
Read 1 Line of Data
fid = fopen(‘mydata.dat’, ‘r’); % open file
% for reading.
% Read-in one line of data corresponding
% to Joe’s entry.
[name,type,x,y,answer] =…
textread(fid,’%s%s%f%d%s’,1,…
’headerlines’,1);
fclose(fid); % close file.
Writing formatted data.
% open file for writing.
fid = fopen(‘out.txt’,’w’);
% Write out Joe’s info to file.
fprintf(fid,’%s %s %f %d…
%s\n’,name,type,x,y,answer);
fclose(fid); % close the file.
Keeping a record
• To keep a record of your session, use the diary
command:
diary filename
x=3
diary off
This will keep a diary called filename showing
the value of x (your work for this session).
Timing
• Use tic, toc to determine the running time
of an algorithm as follows:
tic
commands…
toc
This will give the elapsed time.
Factorial using a for loop
n=4;
x=1;
for i=1:n
x=x*i;
end
disp('The value of factorial of 4 is')
disp(x)