Matlab Tutorial
Matlab Tutorial
EECS 639
August 31, 2016
Matlab Basics
• To start Matlab: Select MATLAB on the menu (if
using Windows). Type “matlab” on the
command line (if using Linux).
Getting Help and
Looking Up Functions
• To get help on a function type “help function_name”,
e.g., “help plot”.
• To find a topic, type “lookfor topic”, e.g., “lookfor matrix”
Matlab’s Workspace
• who, whos – current workspace vars.
• 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.
• 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.
• 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.
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.
• ones(m,n) % m*n matrix with all ones.
Logical Conditions
• ==, <, >, <=, >=, ~= (not equal), ~ (not)
• & (element-wise logical and), | (or)
• find(‘condition’) – Return indices of A’s
elements that satisfies the condition.
• Example: A = [7 6 5; 4 3 2];
find (‘A == 3’); --> returns 5.
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!
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.
For loops
• x = 0;
for i=1:2:5 % start at 1, increment by 2
x = x+i; % end with 5.
end
Here m = 2 and n = 3.
Graphics (3)
• 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.
diary filename
x=3
diary off
tic
commands…
toc
% Backward summation
backwardsum = 0;
for i=10:-1:1
backwardsum = backwardsum+1/(i^2);
end;
Interactive Example (2)
• Write a Matlab function to multiply two
n-by-n matrices A and B. (Do not use
built-in functions.)
Solution
function [C] = matrix_multiply(A,B,n)
C = zeros(n,n);
for i=1:n
Can this code be written so that it
for j=1:n
runs faster?
for k=1:n
C(i,j) = C(i,j) + A(i,k)*B(k,j);
end;
end; Hint: Use vectorization.
end;
Solution
• Script to use for testing:
n = 10;
A = rand(n,n);
B = rand(n,n);
C = matrix_multiply(A,B,n);