Title: Introduction to Matlab
1Introduction to Matlab
By Jafar Muhammadi April 2005
2MATrix LABoratory
- www.mathworks.com
- Advantages of MATLAB
- Ease of use
- Platform independence
- Predefined functions
- Plotting
- Disadvantages of MATLAB
- Can be slow
- Expensive
3Matlab environment
- Matlab construction
- Core functionality as compiled C-code, m-files
- Additional functionality in toolboxes (m-files)
- Today Matlab programming (construct own m-files)
Contr. Syst.
Sig. Proc
User defined
Core m-files
C-kernel
4Matlab Desktop
Launch Pad
Command Window
History
5Matlab Desktop
Workspace
Command Window
Current DIrectory
6Matlab Help
7Matlab Editor
Color keyed text with auto indents
tabbed sheets for other files being edited
8MATLAB Basics
- A program can be input
- command by command using the command line (lines
starting with on the MATLAB desktop) - as a series of commands using a file(a special
file called M-file) - If a command is followed by a semicolon (),
result of the computation is not shown on the
command window
9Data Types
- All numbers are double precision
- Text is stored as arrays of characters
- You dont have to declare the type of data
(defined when running) - MATLAB is case-sensitive!!!
10Data Types
11Variables
- Variable is a name given to a reserved location
in memory - class_code 111
- number_of_students 65
- name Jafar Muhammadi'
- radius 5
- area pi radius2
- Use meaningful names for variables
- MATLAB variable names
- must begin with a letter
- can contain any combination of letters, numbers
and underscore (_) - must be unique in the first 31 characters
- MATLAB is case sensitive name, Name and
NAME are considered different variables - Never use a variable with the same name as a
MATLAB command - Naming convention use lowercase letters
12Variables
- Initialization using assignment statements
- x 5
- x 5
- y x 1
- y 6
- vector 1 2 3 4
- vector 1 2 3 4
- matrix 1 2 3 4 5 6
- matrix 1 2 3 4 5 6
- matrix 1 2 3 4 5
- ??? Error
- a 5 (24)
- a 5 6
13Variables
- Initialization using shortcut statements
- colon operator ? firstincrementlast
- x 1210
- x 1 3 5 7 9
- y 00.10.5
- y 0 0.1 0.2 0.3 0.4 0.5
14Variables
- transpose operator ? '
- u 13 '
- u 1 2 3
- v u u
- v 1 1 2 2 3 3
- v u' u'
- v 1 2 3 1 2 3
15Variables
- Initialization using built-in functions
- zeros()
- x zeros(2)
- x 0 0 0 0
- z zeros(2,3)
- z 0 0 0 0 0 0
- ones(), size(), length()
- y zeros(1,4)
- y 0 0 0 0
- t zeros( size(z) )
- t 0 0 0 0 0 0
16Matrices
17Variables
- Initialization using keyboard input
- input()
- value input( 'Enter an input value ' )
- Enter an input value 1.25
- value 1.2500
- name input( 'What is your name ', 's' )
- What is your name Selim
- name Selim
18Matrices, Colon Operator
- Creating new matrices from an existing matrix
C 1,2,5 -1,0,1 3,2,-1 0,1,4 F C(, 23)
2,5 0,1 2,-1 1,4
19Matrices, Colon Operator
- Creating new matrices from an existing matrix
C 1,2,5 -1,0,1 3,2,-1 0,1,4 E C(23,)
-1 0 1 3 2 -1
20Matrices, Colon Operator
- Creating new matrices from an existing matrix
C 1,2,5 -1,0,1 3,2,-1 0,1,4 G C(34,12)
3,2 0,1
21Matrices, Colon Operator
- Variable_name astepb
- time 0.00.52.5
- time 0.0, 0.5, 1.0, 1.5, 2.0, 2.5
- Negative increment
- values 10-12
- values 10, 9, 8, 7, 6, 5, 4, 3, 2
22Subarrays
- Array indices start from 1
- x -2 0 9 1 4
- x(2)
- ans 0
- x(4)
- ans 1
- x(8)
- ??? Error
- x(-1)
- ??? Error
23Subarrays
- y 1 2 3 4 5 6
- y(1,2)
- ans 2
- y(2,1)
- ans 4
- y(2)
- ans 4 (column major order)
24Subarrays
- y 1 2 3 4 5 6
- y(1,)
- ans 1 2 3
- y(,2)
- ans 2 5
- y(2,12)
- ans 4 5
- y(1,2end)
- ans 2 3
- y(,2end)
- ans 2 3 5 6
25Subarrays
- x -2 0 9 1 4
- x(2) 5
- x -2 5 9 1 4
- x(4) x(1)
- x -2 5 9 -2 4
- x(8) -1
- x -2 5 9 -2 4 0 0
-1
26Subarrays
- y 1 2 3 4 5 6
- y(1,2) -5
- y 1 -5 3 4 5 6
- y(2,1) 0
- y 1 -5 3 0 5 6
- y(1,2end) -1 9
- y 1 -1 9 0 5 6
27Subarrays
- y 1 2 3 4 5 6 7 8 9
- y(2end,2end) 0
- y 1 2 3 4 0 0 7
0 0 - y(2end,2end) -1 5
- ??? Error
- y(2,1 3) -2
- y 1 2 3 -2 0 -2 7
0 0
28Special Values
- pi ? value up to 15 significant digits
- i, j sqrt(-1)
- Inf infinity (such as division by 0)
- NaN Not-a-Number (such as division of zero by
zero) - clock current date and time as a vector
- date current date as a string (e.g. 16-Feb-2004)
- eps epsilon
- ans default variable for answers
29Displaying Data
- The disp( array ) function
- disp( 'Hello' )
- Hello
- disp(5)
- 5
- disp( 'Bilkent ' 'University' )
- Bilkent University
- name 'Selim' disp( 'Hello ' name )
- Hello Selim
30Displaying Data
- The num2str() and int2str() functions
- d num2str(16) '-Feb-' num2str(2004)
- disp(d)
- 16-Feb-2004
- x 23.11
- disp( 'answer ' num2str(x) )
- answer 23.11
- disp( 'answer ' int2str(x) )
- answer 23
31Displaying Data
- The fprintf( format, data ) function
- d integer
- f floating point format
- e exponential format
- \n new line character
- \t tab character
32Displaying Data
- fprintf( 'Result is d', 3 )
- Result is 3
- fprintf( 'Area of a circle with radius d is f',
3, pi32 ) - Area of a circle with radius 3 is 28.274334
- x 5
- fprintf( 'x 3d', x )
- x 5
- x pi
- fprintf( 'x 0.2f', x )
- x 3.14
- fprintf( 'x 6.2f', x )
- x 3.14
- fprintf( 'x d\ny d\n', 3, 13 )
- x 3y 13
33Data Files
- save filename var1 var2
- save homework.mat x y ? binary
- save x.dat x ascii ? ascii
- load filename
- load filename.mat ? binary
- load x.dat ascii ? ascii
34MATLAB Basics Scalar Operations
- variable_name expression
- addition a b ? a b
- subtraction a - b ? a - b
- multiplication a x b ? a b
- division a / b ? a / b
- exponent ab ? a b
35MATLAB Basics Scalar Operations
- x 3 2 6 / 2
- x ?
- Processing order of operations is important
- parenthesis (starting from the innermost)
- exponentials (left to right)
- multiplications and divisions (left to right)
- additions and subtractions (left to right)
- x 3 2 6 / 2
- x 9
36Arithmetic Operators
37Relational and Logical Operators
38Matrices
39MATLAB Basics Built-in Functions
- result function_name( input )
- abs, sign
- log, log10, log2
- exp
- sqrt
- sin, cos, tan
- asin, acos, atan
- max, min
- round, floor, ceil, fix
- mod, rem
- help elfun
40MATLAB Basics Useful Commands
- help command ? Online help
- lookfor keyword ? Lists related commands
- which ? Version and location info
- clear ? Clears the workspace
- clc ? Clears the command window
- diary filename ? Sends output to file
- diary on/off ? Turns diary on/off
- who, whos ? Lists content of the workspace
- more on/off ? Enables/disables paged output
- Ctrlc ? Aborts operation
- ? Continuation
- ? Comments
41The programming environment
- Matlab cant tell if identifier is variable or
function - gtgt ztheta
- Matlab searches for identifier in the following
order - 1. variable in current workspace
- 2. built-in variable
- 3. built-in m-file
- 4. m-file in current directory
- 5. m-file on search path
- Note m-files can be located in current
directory, or in path
42Script files
- Script-files contain a sequence of Matlab
commands
factscript.m
FACTSCRIPT Compute n-factorial, n!12...n y
prod(1n)
- Executed by typing its name
- gtgt factscript
- Operates on variables in global workspace
- Variable n must exist in workspace
- Variable y is created (or over-written)
- Use comment lines (starting with ) to document
file!
43Functions
- Functions describe subprograms
- Take inputs, generate outputs
- Have local variables (invisible in global
workspace) - output_arguments function_name(input_arguments)
- Comment lines
- ltfunction bodygt
factfun.m
function zfactfun(n) FACTFUN Compute
factorial ZFACTFUN(N) z prod(1n)
gtgt yfactfun(10)
44Scripts or function when use what?
- Functions
- Take inputs, generate outputs, have internal
variables - Solve general problem for arbitrary parameters
- Scripts
- Operate on global workspace
- Document work, design experiment or test
- Solve a very specific problem once
- Exam all problems will require you to write
functions
facttest.m
FACTTEST Test factfun N50yfactfun(N)
45Flow control - selection
- The if-elseif-else construction
if ltlogical expressiongt ltcommandsgt elseif
ltlogical expressiongt ltcommandsgt else
ltcommandsgt end
if heightgt170 disp(tall) elseif heightlt150
disp(small) else disp(average) end
46Logical expressions
- Relational operators (compare arrays of same
sizes) - (equal to) (not equal) lt (less
than) lt (less than or equal to)gt (greater
than) gt (greater than or equal to) - Logical operators (combinations of relational
operators) - (and) (or) (not)
- Logical functionsxorisemptyanyall
if (xgt0) (xlt10) disp(x is in range
0,10) else disp(x is out of range) end
47Flow control repetition
- Repeats a code segment a fixed number of times
for indexltvectorgt ltstatementsgt end The
ltstatementsgt are executed repeatedly.At each
iteration, the variable index is assigneda new
value from ltvectorgt.
for k112 kfacprod(1k)
disp(num2str(k), ,num2str(kfac))end
48Example selection and repetition
fact.m
function yfact(n) FACT Display factorials of
integers 1..n if nargin lt 1 error(No input
argument assigned) elseif n lt 0 error(Input
must be non-negative) elseif abs(n-round(n)) gt
eps error(Input must be an integer) end for
k1n kfacprod(1k) disp(num2str(k),
,num2str(kfac)) y(k)kfac end
49Flow control conditional repetition
while ltlogical expressiongt ltstatementsgt end
ltstatementsgt are executed repeatedly as long as
the ltlogical expressiongt evaluates to true
k1 while prod(1k)Inf, kk1
end disp(Largest factorial in
Matlab,num2str(k-1))
50Programming tips and tricks
- Programming style has huge influence on program
speed!
slow.m
fast.m
tic X-2500.1250 for ii1length(x) if
x(ii)gt0, s(ii)sqrt(x(ii)) else
s(ii)0 end end toc
tic x-2500.1250 ssqrt(x) s(xlt0)0 toc
Loops are slow Replace loops by vector
operations! Memory allocation takes a lot of
time Pre-allocate memory! Use profile to find
code bottlenecks!
51Image Processing With Matlab
- Image Processing With Matlab
52Read an Image
- Read in an image
- Validates the graphic format
- (bmp, hdf, jpeg, pcx, png, tiff, xwd)
- Store it in an array
- clear, close all
- I imread(pout.tif)
- X, map imread(pout.tif)
53Digital Image Representation
54Display an Image
55MATLAB Image Types
- Indexed images m-by-3 color map
- Intensity images 0,1 or uint8
- Binary images 0,1
- RGB images m-by-n-by-3
56Binary images
57Intensity Images
58RGB images
59Histogram Equalization
- Histogram distribution of intensities
- figure, imhist(I)
- Equalize Image (contrast)
- I2 histeq(I)
- figure, imshow(I2)
- figure, imhist(I2)
60Histogram Equalization (cont.)
61Histogram Equalization (cont.)
62Write the Image
- Validates the extension
- Writes the image to disk
- imwrite(I2, pout2.png)
- imwrite(I2, pout2.png, BitDepth, 4)
63Morphological Opening
- Remove objects that cannot completely contain a
structuring element - Estimate background illumination
- clear, close all
- I imread(rice.tif)
- imshow(I)
- background imopen(I, strel(disk, 15))
- imshow(background)
64Morphological Opening (cont.)
65Subtract Images
- Create a more uniform background
- I2 imsubtract(I, background)
- figure, imshow(I2)
66Adjust the Image Contrast
- stretchlim computes low hight to be mapped into
bottom top - I3 imadjust(I2, stretchlim(I2), 0 1)
- figure, imshow(I3)
67Apply Thresholding to the Image
- Create a binary thresholded image
- Compute a threshold to convert the intensity
image to binary - Perform thresholding creating a logical matrix
(binary image) - level graythresh(I3)
- bw im2bw(I3, level)
- figure, imshow(bw)
68Apply Thresholding to the Image (cont.)
69Labeling Connected Components
- Determine the number of objects in the image
- Accuracy
- (size of objects, approximated background,
connectivity parameter, touching objects) - labeled, numObjects bwlabel(bw, 4)
- numObjects 80
- max(labeled())
70Select and Display Pixels in a Region
- Interactive selection
- grain imcrop(labeled)
- Colormap creation function
- RGB_label label2rgb(labeled,
- _at_spring, c, shuffle)
- imshow(RGB_label)
- rect 15 25 10 10
- roi imcrop(labeled, rect)
71Object Properties
- 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
72Statistical Properties of Objects
- max(allgrains) 695
- Return the component label of a grain size
- biggrain find(allgrains 695) 68
- Mean grain size
- mean(allgrains) 249
- Histogram (bins)
- hist(allgrains, 20)
73Statistical Properties of Objects (cont.)
74Storage Classes
- double (64-bit), uint8 (8-bit), and uint16
(16-bit) - Converting (rescale or offset)
- double
- im2double (automatic rescale and offsetting)
- RGB2 im2uint8(RGB1)
- im2uint16
- imapprox (reduce number of colors indexed
images)
75Image Types
- Index
- Data matrix (uint8, uint16, double)
- Colormap matrix (m x 3 array of double 0 1)
- Intensity (black 0, white ?)
- Binary (0, 1)
- B logical(uint8(round(A))) (logical flag on)
- B A (logical flag off)
- RGB (m x n x 3 of truecolor)
76Converting Image Types
- dither
- gray2ind
- grayslice
- im2bw
- ind2gray
- ind2rgb
- mat2gray
- rgb2gray
- rgb2ind
77Image Arithmetic
- imabsdiff
- imadd
- imcomplement
- imdivide
- imlincomb
- immultiply
- imsubtract
78Adding Images
- 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)
79Adding Images (cont.)
80Adding Images (cont.)
81Subtracting Images
- Background of a scene
- rice imread(rice.tif)
- background imopen(rice, strel(disk, 15))
- rice2 imsubtract(rice, background)
- imshow(rice), figure, imshow(rice2)
- Negative values
- imabsdiff
82Subtracting Images (cont.)
83Multiplying Images
- Scaling multiply by a constant
- (brightens gt1, darkens lt1)
- Preserves relative contrast
- I imread(moon.tif)
- J immultiply(I, 1.2)
- imshow(I)
- figure, imshow(J)
84Multiplying Images (cont.)
85Dividing Images (Ratioing)
- I imread(rice.tif)
- background imopen(I, strel(disk, 15))
- Ip imdivide(I, background)
- imshow(Ip, )
- Linear combination only truncates the final
result - K imlincomb(.5, I, .5, I2)
86Dividing Images (cont.)
87Coordinate Systems
- Pixel Coordinates
- Discrete unit (integer)
- (r, c)
- ? (1, 1)
- Spatial Coordinates
- Continuous unit
- (x, y)
- ? (0.5, 0.5)
123
88Non-default Spatial Coordinate System
- A magic(5)
- x 19.5 23.5
- y 8.0 12.0
- image(A, xData, x, yData, y), axis image,
colormap(jet(25))
89Spatial Transformations
- Map pixel locations in an input image to new
locations in an output image - Resizing
- Rotation
- Cropping
90Resizing Images
- Change the size of an image
- I imread(ic.tif)
- J imresize(I, 1.25)
- K imresize(I, 100 150)
- figure, imshow(J)
- figure, imshow(K)
91Resizing Images (cont.)
92Rotating Images
- Rotate an image by an angle in degrees
- I imread(ic.tif)
- J imrotate(I, 35, bilinear)
- imshow(I)
- figure, imshow(J)
93Rotating Images (cont.)
94Functions List
95Image Display
96Image File I/O
97Geometric Operations
98Pixel Values and Statistics
99Image Analysis
100Image Enhancement
101Linear Filtering
102Image Transforms
103Binary Image Operations
104Color Space Conversions
105Image Types and Type Conversions
106Demos