Download presentation
Presentation is loading. Please wait.
1
Matlab Tutorial
2
Matrices
3
Matrices
4
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
5
Images and Matrices How to build a matrix (or image)?
>> B = zeros(3,3) B = >> C = ones(3,3) C = >>imshow(A) (imshow(A,[]) to get automatic pixel range)
6
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
7
Operating on whole Matrices
8
Special matrix operators
Some operators must be handled with care: A = [1 2 ; 4 5] B = A * A prints B = A .* A prints Element by element multiplication
9
Submatrices A matrix can be indexed using another matrix, to produce a subset of its elements: a = [ ] b = [3 5 6] c = a(b):
10
Submatrices To get a subsection of a matrix, we can produce the index matrix with the colon operator: a(2:5) prints ans = 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 = [ ]
11
loops ‘for’ loops in MATLAB iterate over matrix elements: b = 0
for i = [ ] b = b + i; end Result: 29 Note: The MATLAB way to write that program would have been: b = sum([ ]); Avoid loops if possible !
12
loops The typical ‘for’ loop looks like: for i = 1:6 … end
Which is the same as: for i = [ ]
13
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
14
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
15
Manipulations & Calculations on matrices
Transpose (‘), inverse (inv) Matrix arithmetic: +, -, *, /, ^ Elementwise arithmetic: .*, ./, .^ Functions Vectorized sin, cos, etc.
16
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
17
Control Structures
18
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
19
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;
20
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,
21
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
22
for for n=1:1:4, subplot(2,2,n) plot(a(:,1),a(:,n+1)) title(num2str(n)) end
23
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
24
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
25
Miscellaneous Diary: Recording a session
diary filename diary off tic, toc bracketing code to measure execution time
26
Once again: AVOID LOOPS
27
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 =
28
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 =
29
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 =
30
Flow Control while, expression, statements, end Indx=1; while A(Indx)<6 A(Indx)=0; Indx=Indx+1; end A = A =
31
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 %
32
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.
33
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;
34
Composition of MATLAB
35
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];
36
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 = 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 =
37
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 = imread imshow size
38
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 = 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
39
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 = 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
40
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
41
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
42
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…..
43
Histograms
44
Image reading and showing
imread imshow
45
Image Histogram imhist
46
Histogram Equalization
histeq
48
Noise
49
Adding Noise Filtering Noise imnoise medfilt2
50
Add Image to noise
51
Median Filtering removes noise
52
Median Filtering removes Gaussian noise
imnoise fspecial imfliter
53
FSPECIAL creates special 2D filters
54
Imfilter – multidimensional filtering
55
Thresholding
56
Thresholding
57
IM2BW – converting to binary by thresholding
58
Repeated thresholding
59
Separating background by thresholding
60
Feature Extraction Extracting features: Corner Center point
61
Edge Detection
62
Example of kernel-based filtering - Sobel
Edge Detection edge Example of kernel-based filtering - Sobel
63
Edge, Sobel and Prewitt
64
Roberts, Laplacian, Zero-cross, Canny edge detection methods
65
Use of threshold in Sobel affects what is found
66
“Laplacian of Gaussian” filtering is often better
67
Canny Filter is even better – this is a major invention with many applications in robotics.
Can one invent a better one?
68
Edge Detection with gray and binary images
Many variants of combining thresholding and edge detection exist
69
EDGE DETECTION IN MATLAB
70
Hough Transform
71
Hough Transform Hough Transform has links to Fourier, Radon and Neural Nets. A deep concept
72
Camera Calibration
73
Calibration of Cameras Matrix/vector multiplication
74
Sequences of operations
75
Noise, filtering and histogramming
76
Fourier Transform in MATLAB
77
Other data MATLAB can also handle Movies 3D objects …
78
Sources Rolf Lakaemper Fred Annexstein Jason Rife Hyunki Lee
Amin Allalou
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.