Matlab Tutorial
Matrices
Matrices
Matrices Rows and columns are always numbered starting at 1 Matlab matrices are of various types to hold different kinds of data (usually floats or integers) A single number is really a 1 x 1 matrix in Matlab! Matlab variables are not given a type, and do not need to be declared Any matrix can be assigned to any variable
Images and Matrices How to build a matrix (or image)? 4 5 6 7 8 9 >> B = zeros(3,3) B = 0 0 0 0 0 0 >> C = ones(3,3) C = 1 1 1 1 1 1 >>imshow(A) (imshow(A,[]) to get automatic pixel range)
Building Matrices Building matrices with [ ]: A = [2 7 4] B = [ A A ] 2 7 4 2 7 4 2 7 4 3 8 9 ? 2 7 4 2 7 4 3 8 9 3 8 9
Operating on whole Matrices
Special matrix operators Some operators must be handled with care: A = [1 2 ; 4 5] B = A * A prints 9 12 24 33 B = A .* A prints 1 4 16 25 Element by element multiplication
Submatrices A matrix can be indexed using another matrix, to produce a subset of its elements: a = [100 200 300 400 500 600 700] b = [3 5 6] c = a(b): 300 500 600
Submatrices To get a subsection of a matrix, we can produce the index matrix with the colon operator: a(2:5) prints ans = 200 300 400 500 This works in 2-D as well, e.g. c(2:3, 1:2) produces a 2 x 2 submatrix. The rows and columns of the submatrix are renumbered. a = [100 200 300 400 500 600 700]
loops ‘for’ loops in MATLAB iterate over matrix elements: b = 0 for i = [ 3 9 17] b = b + i; end Result: 29 Note: The MATLAB way to write that program would have been: b = sum([ 3 9 17]); Avoid loops if possible !
loops The typical ‘for’ loop looks like: for i = 1:6 … end Which is the same as: for i = [1 2 3 4 5 6]
Famous Matrix Manipulation Algorithms Singular value decomposition---[U,S,V]=svd(A) Eigenvalues and eigenvectors---[V,D] = eig(A) Orthogonal-triangular decomposition- [Q,R]=qr(A) LU factorization --[L,U] = lu(A) Matrix rank -- a=rank(A) Condition number -- a=cond(A) Linear systems: A\b solves A*x = b
Constructing Matrices Basic built-ins: All zeroes, ones: zeros, ones Identity: eye Random: rand (uniform), randn (unit normal) Ranges: m:n, m:i:n (i is step size) Composing big matrices out of small matrix blocks repmat(A, m, n): “Tile” a big matrix with m x n copies of A
Manipulations & Calculations on matrices Transpose (‘), inverse (inv) Matrix arithmetic: +, -, *, /, ^ Elementwise arithmetic: .*, ./, .^ Functions Vectorized sin, cos, etc.
Deconstructing Matrices Indexing individual entries by row, col: A(1, 1) is upper-left entry Ranges: e.g., A(1:10, 3), A(:, 1) Matrix to vector and vice versa by column: B = A(:), A(:) = B Transpose to use row order find: Indices of non-zero elements
Control Structures
Control Structures Expressions, relations (==, >, |, &, functions, etc.) if/while expression statements end Use comma to separate expression from statements if on same line if a == b & isprime(n), M = inv(K); else M = K; end for variable = expression statements end for i=1:2:100, s = s / 10; end
function [c,d,e]= pyt(a,b) % returns the hypotenuse in a right angle % triangle according to Pythagoras theorem. % c is the hypotenuse, % d and e are the two sharp angles c=sqrt(a.^2+b.^2); d=atan(b./a); e=pi/2-d;
if: if (A > B), statement; if i==1, elseif (A< B), statement; elseif ~A, statement; else, end if i==1, statement; end if res(n,2) ~= 0, else,
switch switch (rem(n,3) ==0) & (rem(n,2)==0) case 0 disp('n is not dividable by 6') case 1 disp('n is dividable by 6') otherwise error('This is impossible.') end
for for n=1:1:4, subplot(2,2,n) plot(a(:,1),a(:,n+1)) title(num2str(n)) end
while a = 4; fa = sin(a); b = 2; fb = sin(b); while a - b > 5 * eps, x = (a+b)/2; fx = sin(x); if sign(fx) == sign(fa), a = x; fa=fx; break; else b = x; fb = fx; end
Plotting 2-D vectors: plot(x, y) 3-D: plot3(x, y, z)(space curve) plot(0:0.01:2*pi, sin(0:0.01:2*pi)) 3-D: plot3(x, y, z)(space curve) Surfaces meshgrid makes surface from axes, mesh plots it [X,Y] = meshgrid(-2:.2:2, -2:.2:2); Z = X .* exp(-X.^2 - Y.^2); mesh(Z) surf: Solid version of mesh Saving figures, plots: print –depsc2 filename
Miscellaneous Diary: Recording a session diary filename diary off tic, toc bracketing code to measure execution time
Once again: AVOID LOOPS
Logical Conditions equal (==) , less than and greater than (< and >), not equal (~=) and not (~) find(‘condition’) - Returns indexes of A’s elements that satisfies the condition. >> [row col]=find(A==7) row = 3 col = 1 >> [row col]=find(A>7) 3 col = 2 >> Indx=find(A<5) Indx = 1 2 4 7 A = 2 3 5 6 7 8 9
Flow Control A = 1 2 0 2 1 2 0 2 1 Flow control in MATLAB - if, else and elseif statements (row=1,2,3 col=1,2,3) if row==col A(row, col)=1; elseif abs(row-col)==1 A(row, col)=2; else A(row, col)=0; end A = 1 2 0 2 1 2 0 2 1
Flow Control A = 1 2 0 2 1 2 0 2 1 Flow control in MATLAB - for loops for row=1:3 for col=1:3 if row==col A(row, col)=1; elseif abs(row-col)==1 A(row, col)=2; else A(row, col)=0; end A = 1 2 0 2 1 2 0 2 1
Flow Control while, expression, statements, end Indx=1; while A(Indx)<6 A(Indx)=0; Indx=Indx+1; end A = 2 3 5 6 7 8 9 A = 0 2 3 0 5 6 7 8 9
M-Files Any text file ending in “.m” Use path or addpath to tell Matlab where code is (non-persistent?) Script: Collection of command line statements Function: Take argument(s), return value(s). First line defines: function y = foo(A) function [x, y] = foo2(a, M, N) Comment: Start line with %
Working with M-Files M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output. MATLAB functions: Are useful for extending the MATLAB language for your application. Can accept input arguments and return output arguments. Store variables in a workspace internal to the function.
Working with M-Files Create a new empty m-file function B=test(I) [row col]=size(I) for r=1:row for c=1:col if r==c A(r, c)=1; elseif abs(r-c)==1 A(r, c)=2; else A(r, c)=0; end B=A;
Composition of MATLAB
Examples Try these 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 as follows. >>M= [ 1 2 3; 4 5 6; 7 8 9];
Projection Say you want to extract some rows and columns of a matrix. This is called a projection. We simply give the subset of rows and columns as parameters, as follows >> M11=M(2:3 , 2:3) M11 = 5 6 8 9 To specify all elements in a given dimension one can use ':‘ So to get all rows but just columns 1 and 2, we type >> A= M( :, 1:2) A = 1 2 4 5 7 8
WORKING WITH IMAGES in MatLab Let’s talk about image files and their formats….. Color vs GrayScale Basic Image Processing functions: Reading in an image: >> img1=imread('Water lilies.jpg'); Displaying an image: >> imshow(img1); Finding out size of an image: >> size(img1); >> size(img1) ans = 600 800 3 imread imshow size
variable imgsmall WORKING WITH IMAGES in MatLab Cropping an image: >> imgsmall=img1(200:300,300:400,1:3); >> imshow(imgsmall) >> imgsmall=img1(150:250,350:450,1:3); >> size(imgsmall) ans = 101 101 3 Exercise: 1. Find 2 images online 2. Crop them to the same size 3. Add the two images together. 4. Display resulting image Advanced Exercise: Rescale images to same size then add them See next slide to see HOWTO rescale variable imgsmall
ReScaling linspace round We can rescale by changing the number of rows and columns, yet preserve the information in the image >> [rows, cols, colors]= size(img1) rows = 600 cols = 800 colors = 3 % Increase the number of rows >> stretchfactor = 1.5 >> rowVec= linspace(1,rows,stretchfactor*rows); >> newrows=round(rowVec); >> newimag=img1(newrows,:,:) >> imshow(newimg); % Decrease number of columns >> stretchfactor = 0.75; >> colVec= linspace(1,cols,stretchfactor*cols); >> newcols=round(colVec); >> newimag=newimg(:,newcols,:) >>imshow(newimg) linspace round
Example Program: Inverting an image To invert or to add two images we need to convert to double and then rescale the result back so that it looks like an image InvImg= 1 - double(IMG1)/255; NewImg = uint8(round(InvImg*255))) Imshow(NewImg); uint8
input WORKING WITH IMAGES in MatLab Color Masking Sometimes we want to replace pixels of an image of one or more colors with pixels from another image. It is useful to use a “blue or green screen” in some instances. Find an image with a big plot of one color. First we will replace that color. And then we will find another image for pixel replacement. Let us plot the color values of one chosen row…This will tell us the pixel values of the color we want to replace. v = imread(‘myimg.jpg’) image(v) row= input(‘which row?’); red = v(row,:,1); green = v(row,:,2); blue = v(row,:,3); plot(red,’r’); hold on plot(green,’g’); plot(blue,’b’); input
WORKING WITH IMAGES in MatLab Suppose we want to replace those values whose intensities exceed a threshold value of 160 in each color. v= imread(‘myimg.jpg’); thresh= 160 layer = (v(:,:,1) > thresh) & (v(:,:,2) > thresh) (v(:,:,2) > thresh) mask(:,:,1) = layer; mask(:,:,2) = layer; mask(:,:,3) = layer; If you want to only mask a portion of the image you can use something like… >> mask(700:end,:,:)= false; Which sets the mask so that we do not affect rows 700 and above To reset the color to red >>newv = v; >>newv(mask)(1) = 255 Or to replace pixels from a different image w use… >> newv(mask) = w(mask); Let us try to do this with a blue screen…..
Histograms
Image reading and showing imread imshow
Image Histogram imhist
Histogram Equalization histeq
Noise
Adding Noise Filtering Noise imnoise medfilt2
Add Image to noise
Median Filtering removes noise
Median Filtering removes Gaussian noise imnoise fspecial imfliter
FSPECIAL creates special 2D filters
Imfilter – multidimensional filtering
Thresholding
Thresholding
IM2BW – converting to binary by thresholding
Repeated thresholding
Separating background by thresholding
Feature Extraction Extracting features: Corner Center point
Edge Detection
Example of kernel-based filtering - Sobel Edge Detection edge Example of kernel-based filtering - Sobel
Edge, Sobel and Prewitt
Roberts, Laplacian, Zero-cross, Canny edge detection methods
Use of threshold in Sobel affects what is found
“Laplacian of Gaussian” filtering is often better
Canny Filter is even better – this is a major invention with many applications in robotics. Can one invent a better one?
Edge Detection with gray and binary images Many variants of combining thresholding and edge detection exist
EDGE DETECTION IN MATLAB
Hough Transform
Hough Transform Hough Transform has links to Fourier, Radon and Neural Nets. A deep concept
Camera Calibration
Calibration of Cameras Matrix/vector multiplication
Sequences of operations
Noise, filtering and histogramming
Fourier Transform in MATLAB
Other data MATLAB can also handle Movies 3D objects …
Sources Rolf Lakaemper Fred Annexstein Jason Rife Hyunki Lee Amin Allalou www.cis.udel.edu/~cer/arv