You are on page 1of 76

Introduction to Matlab

Slides adapted from : Azernikov Sergei, Hanbyu Joo, Wen-Sheng Chu


Outline
1. Introduction
1. Overview
2. Variables
3. Matrix
4. Misc.
2. Image Processing with Matlab
3. References
What & Why
• Matrix Laboratory
– Dynamically typed language
• Variables require no declaration
• Creation by initialization (x=10;)
– All variables are treated as matrices
• Scalar: 1×1 matrix; Vector: N×1 or 1×N matrix
• Calculations are much faster
• Advantages
– Fast implementation and debugging
– Natural matrix operation
– Powerful image processing toolbox
Matlab Main Screen
◼ Command Window
❑ type commands

◼ Current Directory
❑ View folders and m-files

◼ Workspace
❑ View variables
❑ Double click on a variable
to see it in the Array Editor

◼ Command History
❑ view past commands
❑ save a whole session
using diary

Slide credit: İ.Yücel Özbek


Outline
1. Introduction
1. Overview
2. Variables
3. Matrix
4. Misc.
2. Image Processing with Matlab
3. References
Variables
Defining variables

int a; >>a=1;
a=1; >>b=2+4;
double b;
b=2+4;
C/C++ Matlab

Variables are created when they are used

All variables are created as matrices with “some” type


(unless specified)
Variables
a = 1;

b = false;
Variables
A = [1, 2, 3]

B = [1,2,3;4,5,6]

C=[1 2 3;4 5 6;7 8 9]


Variables
D=[1 ; 2 ; 3]

E=[1 2 3]’
Variables
Variables
C = ‘Hello World!';
Variables

A = zeros(3);
B = ones(5);
C = rand(100,2);
D = eye(20);
E = sprintf('%d\n',9);
Matrix Index
Matrix indices begin from 1 (not 0!!!)
Matrix indices must be positive integers

Column-Major Order
Matrix Index
>> A(2,2:3) >> A(2,1:end) >> A(2,:)

ans = ans = ans =

5 6 4 5 6 4 5 6

>> A(:)
ans =

>> A(2,1:2:3) >> A(2,[1 3]) 1


4
ans = ans = 7
2
5
4 6 4 6
8
3
6
9
Matrix Index
Accessing Elements
A = rand(4);
A(2,3)
A(:,2)
A(end,:)
A([1,2],[1,3])
A(1:2,3:end)

http://www.mathworks.com/company/newsletters/articles/matrix-indexing-
in-matlab.html
Matrix Operations
+ addition
- subtraction
* multiplication

^ power
‘ complex conjugate transpose
Matrix Operations

Given A and B:

Addition Subtraction Product Transpose

Slide credit: İ.Yücel Özbek


Matrix Operations
.* element-wise multiplication
./ element-wise division
.^element-wise power

Slide credit: İ.Yücel Özbek


Matrix Operations
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1

x = A(1,:) y = A(3 ,:) b = x .* y c=x./y d = x .^y

x= y= b= c= d=
1 2 3 3 4 -1 3 8 -3 0.33 0.5 -3 1 16 0.33

Slide credit: İ.Yücel Özbek


Matrix Concatenation
X=[1 2], Y=[3 4]
Getting Help
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.
Strings

A =‘vision and geometry’


strfind(A,‘geometry')
strcmp(A,'computer vision')
B = strcat(A,' 12345')
c = [A,' 12345']
D = sprintf('I am %02d years old.\n',9)
int2str, str2num, str2double
http://www.mathworks.com/help/matlab/ref/strings.html
Cell and Structure
• Cells
○ a = {}; a = cell(1)
○ b = {1,2,3}
○ c = {{1,2},2,{3}}
○ D = {'cat','dog','sheep','cow'}
○ E = {'cat',4}

• Structures
○ A = struct('name','1.jpg','height',640,'width',480);
○ b.name = '1.jpg‘

http://www.mathworks.com/help/matlab/matlab_prog/cell-vs-struct-arrays.html
Operators
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than equal to
& And operator
| Or operator
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];

ysddiat@gmail.com
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.
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.
Outline
1. Introduction
1. Overview
2. Variables
3. Loops & Conditions
4. Misc.
2. Image Processing with Matlab
3. References
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 face
case {1}
disp(‘Rolled a 1’);
case {2}
disp(‘Rolled a 2’);
otherwise
disp(‘Rolled a number >= 3’);
end

NOTE: Unlike C, ONLY the SWITCH statement between


the matching case and the next case, otherwise, or end are
executed. (So breaks are unnecessary.)
Break statements
break – terminates execution of for and while
loops. For nested loops, it exits the innermost loop
only.
Outline
1. Introduction
1. Overview
2. Variables
3. Loops and conditions
4. Misc.
2. Image Processing with Matlab
3. References
Flow Control
• if, for, while ….

if (a<3) for ii=1:100


Some Matlab Commands; Some Matlab Commands;
elseif (b~=5) end
Some Matlab Commands;
end for j=1:3:200
Some Matlab Commands;
end

while ((a>3) & (b==5)) for k=[0.1 0.3 -13 12 7 -9.3]


Some Matlab Commands; Some Matlab Commands;
end end

http://www.mathworks.com/help/matlab/control-flow.html
Slide credit: İ.Yücel Özbek
Vectorization
Optimize your code for Matrix operations
Examples tic; i = 0;
for t = 0:.001:1000
i = i + 1;
In other languages: y(i) = sin(t);
end; toc;
Elapsed time is 0.509381 seconds.

tic; t = 0:.001:1000;
In MATLAB: y = sin(t); toc;

Elapsed time is 0.011212 seconds.

http://www.mathworks.com/help/matlab/matlab_prog/vectorization.html
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)

subplot(m,n,1) % Makes an mxn array


for plots. Will place plot in 1st position.

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
Practice Questions

Q2 What best describes the output at


Matlab’s command line?
__mysum=12

Q3 If mysum is initializd to –3 what will be the


output? __9

Q4 If the command z=(x>=3) is executed in the command


line what will be the value of z? [0 1 1]

Q5 Is MATLAB case sensitive ?


Functions in MATLAB
Functions are "self contained" modules of code that accomplish a specific task.
Functions usually "take in" data, process it, and "return" a result. Once a function is
written, it can be used over and over and over again. Functions can be "called" from
the inside of other functions.

Syntax:
function [y , y ,y . . . . , y ] = functionName(arguments)
1 2 3 n

.....
end
where, y . . . . y are output variables.
1 n
Functions Cont.
Define a function in a file named calculateAverage.m that accepts an input vector,
calculates the average of the values, and returns a single result.

function ave = calculateAverage(x)


ave = sum(x(:))/numel(x);
End

Call the function from the command line:

z = 1:99;
ave = calculateAverage(z)

Result:
ave = 50
Scripts and Functions
Two kinds of M-files:

- Scripts, which do not accept input


arguments or return output arguments.
They operate on data in the workspace.

- Functions, which can accept input


arguments and return output
arguments. Internal variables are
local to the function.
M-file functions
function [area,circum] = circle(r)
% [area, circum] = circle(r) returns the
% area and circumference of a circle
% with radius r.
area = pi*r^2;
circum = 2*pi*r;

• Save function in circle.m.


M-file scripts
r = 7;
[area,circum] = circle(r);
% call our circle function.
disp([‘The area of a circle having…
radius ‘ num2str(r) ‘ is ‘…
num2str(area)]);

• Save the file as myscript.m.


Tutorial sources
http://docplayer.net/15715694-Introduction-to-
matlab-basics-reference-from-azernikov-sergei-
mesergei-tx-technion-ac-il.html
Tutorial by Azernikov Sergei.
Interactive Example (1)
Write a Matlab program to compute the following
sum
∑1/i2, for i=1, 2, …, 10
two different ways:
1. 1/1+1/4+…+1/100
2. 1/100+1/81+…+1/1.
Solution
% Forward summation
forwardsum = 0;
for i=1:10
forwardsum = forwardsum+1/(i^2);
end;

% 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;
end; Hint: Use vectorization.
Solution

Script to use for testing:

n = 10;
A = rand(n,n);
B = rand(n,n);
C = matrix_multiply(A,B,n);
M-File

Click to create
a new M-File

• A text file containing script or function


• Extension “.m”
Functions
For example,
Implement your own function Add3()
B = Add3(A)
How?
Create a M-file with the function name
Use the function definition at the beginning

function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)
Functions
Debugging
Breakpoints
Plotting
Plotting functions
plot, plot3d, bar, area, hist, contour, mesh

x = -pi:.1:pi;
y = sin(x);
plot(x,y)
Help & Doc
help functionName
doc functionName
Outline
1. Introduction
1. Overview
2. Variables
3. Matrix
4. Misc.
2. Image Processing with Matlab
3. References
Image Data Structure
• Image as matrices
– Gray image: m×n • Format:
– [0, 255] uint8
– RGB image: m×n×3
– [0, 1] double
I(1,1,3)

I(1,1,1) I(1,n,3)

I(m,n,3)

n I(m,n,1)
Image I/O/Display
% Read image (support bmp, jpg, png, ppm, etc)
I = imread('lena.jpg');

% Save image
imwrite(I, 'lena_out.jpg');

% Display image
imshow(I);

% Alternatives to imshow
imagesc(I);
imtool(I);
image(I);
Image Conversions
% Type conversion
I1 = im2double(I);
I2 = im2uint8(I);

% Convert from RGB to grayscale


I3 = rgb2gray(I);
Image Operations
% Resize image as 60% smaller
Ires = imresize(I, 0.6);

% Crop image from user’s input


imshow(I);
Rect = getrect;
Icrp = imcrop(I, Rect);

% Rotate image by 45 degrees


Irot = imrotate(I, 45);

% Affine transformation
A = [1 0 0; .5 1 0; 0 0 1];
tform = maketform('affine', A);
Itran = imtransform(I, tform);
Image Filtering / Convolution
• A filter (or called mask, kernel, neighborhood) is N×N matrix.

• Filters help us perform different kinds of operations:


Blurring Sharpening Edge Denoise
Outline
1. Introduction
1. Overview
2. Variables
3. Matrix
4. Misc.
2. Image Processing with Matlab
3. References
References
More tutorials
• Matlab course @ ETHZ (http://goo.gl/W2jmZJ)
• Introductory Digital Processing @ IIT (http://goo.gl/U0osD2)

Open source CV algorithms with Matlab interface


• VLFeat (http://www.vlfeat.org/)
• Piotr Dollar’s toolbox (http://vision.ucsd.edu/~pdollar/toolbox/)
• Mexopencv (http://www.cs.stonybrook.edu/~kyamagu/mexopencv/)
References
− Matlab Documentation
• http://www.mathworks.com/help/matlab/

− Cheat Sheets
• http://web.mit.edu/18.06/www/Spring09/matlab-cheatsheet.pdf
• http://www.geog.ucsb.edu/~pingel/210b/general/matlab_refcard.pdf
Thank you!

You might also like