MATLAB
Tutorial Course
A.H. Taherinia
Matlab Environment Contents Continued Desktop tools matrices - - PowerPoint PPT Presentation
M ATLAB Tutorial Course A.H. Taherinia Matlab Environment Contents Continued Desktop tools matrices Logical &Mathematical operations Handle Graphics 1 MATLAB Desktop Tools Command Window Command History Help Browser
A.H. Taherinia
Continued Desktop tools matrices
1
2
3
» a = 2; » b = 5; » a^b ans = 32 » x = 5/2*pi; » y = sin(x) y = 1 » z = asin(y) z = 1.5708 » a = 2; » b = 5; » a^b ans = 32 » x = 5/2*pi; » y = sin(x) y = 1 » z = asin(y) z = 1.5708 Results assigned to “ans” if name not specified () parentheses for function inputs Semicolon suppresses screen output
MATLAB as a calculator Assigning Variables A Note about Workspace: Numbers stored in double-precision floating point format
» -5/(4.8+5.32)^2
ans =
» (3+4i)*(3-4i)
ans = 25
» cos(pi/2)
ans = 6.1230e-017
» exp(acos(0.3))
ans = 3.5470
» -5/(4.8+5.32)^2
ans =
» (3+4i)*(3-4i)
ans = 25
» cos(pi/2)
ans = 6.1230e-017
» exp(acos(0.3))
ans = 3.5470
4
whos: List current variables clear: Clear variables and functions from memory Close: Closes last figures cd: Change current working directory dir: List files in directory echo: Echo commands in M-files format: Set output format
5
6
(>>help)
(>>lookfor)
(>>doc)
7
8
» a=[1 2;3 4] a = 1 2 3 4 » b=[-2.8, sqrt(-7), (3+5+6)*3/4] b =
» b(2,5) = 23 b =
0 0 0 0 23.0000 » a=[1 2;3 4] a = 1 2 3 4 » b=[-2.8, sqrt(-7), (3+5+6)*3/4] b =
» b(2,5) = 23 b =
0 0 0 0 23.0000
Row separator semicolon (;) Column separator space / comma (,)
Use square brackets [ ]
9
4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0.5 4 5 56 23 83 13 10
1 2 Rows (m) 3 4 5 Columns (n) 1 2 3 4 5
1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25
A = A (2,4) A (17)
Rectangular Matrix: Scalar: 1-by-1 array Vector: m-by-1 array 1-by-n array Matrix: m-by-n array
10
» w=[1 2;3 4] + 5 w = 6 7 8 9 » x = 1:5 x = 1 2 3 4 5 » y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4) z = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185 » w=[1 2;3 4] + 5 w = 6 7 8 9 » x = 1:5 x = 1 2 3 4 5 » y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4) z = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
Scalar expansion Creating sequences: colon operator (:) Utility functions for creating matrices.
11
» a=[1 2;3 4] a = 1 2 3 4 » cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24 » a=[1 2;3 4] a = 1 2 3 4 » cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,)
Use square brackets [ ]
4*a
12
» A=[1 5 9;4 3 2.5; 0.1 10 3i+1] A = 1.0000 5.0000 9.0000 4.0000 3.0000 2.5000 0.1000 10.0000 1.0000+3.0000i » A(:,2)=[] A = 1.0000 9.0000 4.0000 2.5000 0.1000 1.0000 + 3.0000i » A(2,2)=[] ??? Indexed empty matrix assignment is not allowed. » A=[1 5 9;4 3 2.5; 0.1 10 3i+1] A = 1.0000 5.0000 9.0000 4.0000 3.0000 2.5000 0.1000 10.0000 1.0000+3.0000i » A(:,2)=[] A = 1.0000 9.0000 4.0000 2.5000 0.1000 1.0000 + 3.0000i » A(2,2)=[] ??? Indexed empty matrix assignment is not allowed.
13
4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0.5 4 5 56 23 83 13 10
1 2 3 4 5 1 2 3 4 5
1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25
A =
A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) A(1:end,end) A(:,end) A(21:end)’
14
» a = [1 2 3 4; 5 6 7 8]; » b = ones(4,3); » c = a*b c = 10 10 10 26 26 26 » a = [1 2 3 4; 5 6 7 8]; » b = ones(4,3); » c = a*b c = 10 10 10 26 26 26 [2x4] [4x3] [2x4]*[4x3] [2x3] a(2nd row).b(3rd column) » a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 4 9 16 5 12 21 32 » a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 4 9 16 5 12 21 32 c(2,4) = a(2,4)*b(2,4)
Array Multiplication 15
16
17
18
» Mass = [-2 10 NaN 30 -11 Inf 31]; » each_pos = Mass>=0
each_pos = 0 1 0 1 0 1 1
» all_pos = all(Mass>=0)
all_pos =
» all_pos = any(Mass>=0)
all_pos = 1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin = 0 1 0 1 0 0 1
» Mass = [-2 10 NaN 30 -11 Inf 31]; » each_pos = Mass>=0
each_pos = 0 1 0 1 0 1 1
» all_pos = all(Mass>=0)
all_pos =
» all_pos = any(Mass>=0)
all_pos = 1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin = 0 1 0 1 0 0 1
= = equal to > greater than < less than >= Greater or equal <= less or equal ~ not & and | or isfinite(),etc. . . . all(), any() find
Note:
19
20
21
22
23
plot, title, xlabel, grid,legend, hold, axis
Property Editor
24
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...) plot(x1, y1, 'clm1', x2, y2, 'clm2', ...) x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z,'fontsize',14); legend('Y data','Z data ,'linewidth',2) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values','fontsize',14); grid on x=[0:0.1:2*pi]; y=sin(x); z=cos(x); plot(x,y,x,z,'fontsize',14); legend('Y data','Z data ,'linewidth',2) title('Sample Plot','fontsize',14); xlabel('X values','fontsize',14); ylabel('Y values','fontsize',14); grid on
25
Title Ylabel Xlabel Grid Legend 26
income = [3.2 4.1 5.0 5.6];
subplot(2,1,1); plot(income); subplot(2,1,2); plot(outgo); income = [3.2 4.1 5.0 5.6];
subplot(2,1,1); plot(income); subplot(2,1,2); plot(outgo); 27
28
29
30
Syntax:
»subplot(2,2,1); » … »subplot(2,2,2) » ... »subplot(2,2,3) » ... »subplot(2,2,4) » ... »subplot(2,2,1); » … »subplot(2,2,2) » ... »subplot(2,2,3) » ... »subplot(2,2,4) » ... subplot(rows,cols,index) subplot(rows,cols,index)
31
32
MATLAB prompt
parameters
33
function y = mean (x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); if m == 1 m = n; end y = sum(x)/m;
Output Arguments Input Arguments Function Name Online Help Function Code
34
eps = 1; while (1+eps) > 1 eps = eps/2; end eps = eps*2 eps = 1; while (1+eps) > 1 eps = eps/2; end eps = eps*2
Flow Control Statements 35
a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end end a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end end
method = 'Bilinear'; switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic')
disp('Unknown method.') end Method is linear method = 'Bilinear'; switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic')
disp('Unknown method.') end Method is linear
Flow Control Statements 36
if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; end; if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; end;
function r = ourrank(X,tol) % rank of a matrix s = svd(X); if (nargin == 1) tol = max(size(X)) * s(1)* eps; end r = sum(s > tol); function r = ourrank(X,tol) % rank of a matrix s = svd(X); if (nargin == 1) tol = max(size(X)) * s(1)* eps; end r = sum(s > tol); function [mean,stdev] = ourstat(x) [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2); function [mean,stdev] = ourstat(x) [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2);
Multiple Input Arguments use ( ) Multiple Output Arguments, use [ ] »r=ourrank(rand(5),.1); »[m std]=ourstat(1:9);
37
38
(bmp, hdf, jpeg, pcx, png, tiff, xwd)
clear, close all; I = imread(‘pout.tif`); [X, map] = imread(‘pout.tif’);
imshow(I)
whos
Name Size Bytes Class ans 291x240 69840 uint8 array Grand total is 69840 elements using 69840 bytes
[0, 1] double [0, 65535] uint16 [0, 255] uint8
figure, imhist(I)
I2 = histeq(I); figure, imshow(I2) figure, imhist(I2)
imwrite(I2, ’pout2.png’); imwrite(I2, ‘pout2.png’, ‘BitDepth’, 4);
I = imread('coins.png'); h = ones(5,5) / 25; I2 = imfilter(I,h); imshow(I), title('Original Image'); figure, imshow(I2), title('Filtered Image')
Median filtering is similar to using an averaging filter, in that each output pixel is set to an average of the pixel values in the neighborhood of the corresponding input pixel. B = medfilt2(A,[m n]) B = medfilt2(A) B = medfilt2(A,'indexed',...)
I = imread('eight.tif'); subplot(2,2,1), imshow(I), title('Original image'); J = imnoise(I,'salt & pepper',0.02); subplot(2,2,2), imshow(J), title('Salt & pepper noise add'); K = imfilter(J, fspecial('average',3)); subplot(2,2,3), imshow(K), title('averaging filter'); L = medfilt2(J,[3 3]); subplot(2,2,4), imshow(L), title('median filter');
imabsdiff imadd imcomplement imdivide imlincomb immultiply imsubtract
I = imread(‘rice.tif’); J = imread(‘cameraman.tif’); K = imadd(I, J); imshow(K)
Brighten an image results saturation RGB = imread(‘flowers.tif’); RGB2 = imadd(RGB, 50); subplot(1, 2, 1); imshow(RGB); subplot(1, 2, 2); imshow(RGB2);
rice = imread(‘rice.tif’); background = imopen(rice, strel(‘disk’, 15)); rice2 = imsubtract(rice, background); imshow(rice), figure, imshow(rice2);
imabsdiff
(brightens >1, darkens <1)
I = imread(‘moon.tif’); J = immultiply(I, 1.2); imshow(I); figure, imshow(J)
I = imread('rice.png'); J = imdivide(I,2); subplot(1,2,1), imshow(I) subplot(1,2,2), imshow(J)
Resizing Rotation Cropping
I = imread(‘ic.tif’); J = imresize(I, 1.25); K = imresize(I, [100 150]); figure, imshow(J) figure, imshow(K)
I = imread(‘ic.tif’); J = imrotate(I, 35, ‘bilinear’); imshow(I) figure, imshow(J)
imshow ic.tif I = imcrop;
Graphical User Interface Design Environment
clear, close all I = imread(‘rice.png’); imshow(I) background = imopen(I, strel(‘disk’, 15)); imshow(background)
I2 = imsubtract(I, background); figure, imshow(I2)
I3 = imadjust(I2, stretchlim(I2), [0 1]); figure, imshow(I3)
image to binary
(binary image) level = graythresh(I3); bw = im2bw(I3, level); figure, imshow(bw)
(size of objects, approximated background, connectivity parameter, touching objects) [labeled, numObjects] = bwlabel(bw, 4); numObjects
{= 80}
max(labeled(:))
grain = imcrop(labeled)
RGB_label = label2rgb(labeled, @spring, ‘c’, ‘shuffle’); imshow(RGB_label); rect = [15 25 10 10]; roi = imcrop(labeled, rect)
Measure object or region properties
graindata = regionprops(labeled, ‘basic’) graindata(51).Area {296} graindata(51).BoundingBox {142.5 89.5 24.0 26.0} graindata(51).Centroid {155.3953 102.1791}
Create a vector which holds just one property for each object
allgrains = [graindata.Area]; whos
max(allgrains)
{ 695 }
biggrain = find(allgrains == 695) { 68 }
mean(allgrains)
{ 249 }
hist(allgrains, 20)
double (64-bit), uint8 (8-bit), and uint16 (16-bit)
double im2double (automatic rescale and offsetting) RGB2 = im2uint8(RGB1); im2uint16 imapprox (reduce number of colors: indexed images)
Data matrix (uint8, uint16, double) Colormap matrix (m x 3 array of double [0 1])
B = logical(uint8(round(A))); (logical flag on) B = +A; (logical flag off)
dither gray2ind grayslice im2bw ind2gray ind2rgb mat2gray rgb2gray rgb2ind
A = cat(4, A1, A2, A3, A4, A5)
FRM3 = MULTI(:, :, :, 3)
imshow(MULTI(:, :, :, 7))
Pixel Coordinates
Discrete unit
(integer)
(r, c) ⎡ = (1, 1)
Spatial Coordinates
Continuous unit (x, y) ⎡= (0.5, 0.5)
123
A = magic(5); x = [19.5 23.5]; y = [8.0 12.0]; image(A, ‘xData’, x, ‘yData’, y), axis image, colormap(jet(25))