Introduction to Matlab - PowerPoint PPT Presentation

1 / 106
About This Presentation
Title:

Introduction to Matlab

Description:

Introduction to Matlab – PowerPoint PPT presentation

Number of Views:147
Avg rating:3.0/5.0
Slides: 107
Provided by: nic46
Category:

less

Transcript and Presenter's Notes

Title: Introduction to Matlab


1
Introduction to Matlab
By Jafar Muhammadi April 2005
2
MATrix LABoratory
  • www.mathworks.com
  • Advantages of MATLAB
  • Ease of use
  • Platform independence
  • Predefined functions
  • Plotting
  • Disadvantages of MATLAB
  • Can be slow
  • Expensive

3
Matlab 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
4
Matlab Desktop
Launch Pad
Command Window
History
5
Matlab Desktop
Workspace
Command Window
Current DIrectory
6
Matlab Help
7
Matlab Editor
Color keyed text with auto indents
tabbed sheets for other files being edited
8
MATLAB 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

9
Data 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!!!

10
Data Types
11
Variables
  • 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

12
Variables
  • 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

13
Variables
  • 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

14
Variables
  • 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

15
Variables
  • 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

16
Matrices
  • Some useful commands

17
Variables
  • 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

18
Matrices, 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
19
Matrices, 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
20
Matrices, 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
21
Matrices, 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

22
Subarrays
  • 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

23
Subarrays
  • y 1 2 3 4 5 6
  • y(1,2)
  • ans 2
  • y(2,1)
  • ans 4
  • y(2)
  • ans 4 (column major order)

24
Subarrays
  • 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

25
Subarrays
  • 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

26
Subarrays
  • 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

27
Subarrays
  • 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

28
Special 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

29
Displaying Data
  • The disp( array ) function
  • disp( 'Hello' )
  • Hello
  • disp(5)
  • 5
  • disp( 'Bilkent ' 'University' )
  • Bilkent University
  • name 'Selim' disp( 'Hello ' name )
  • Hello Selim

30
Displaying 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

31
Displaying Data
  • The fprintf( format, data ) function
  • d integer
  • f floating point format
  • e exponential format
  • \n new line character
  • \t tab character

32
Displaying 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

33
Data 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

34
MATLAB 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

35
MATLAB 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

36
Arithmetic Operators
37
Relational and Logical Operators
38
Matrices
  • More commands

39
MATLAB 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

40
MATLAB 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

41
The 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

42
Script 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!

43
Functions
  • 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)
44
Scripts 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)
45
Flow 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
46
Logical 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
47
Flow 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
48
Example 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
49
Flow control conditional repetition
  • while-loops

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))
50
Programming 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!
51
Image Processing With Matlab
  • Image Processing With Matlab

52
Read 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)

53
Digital Image Representation
54
Display an Image
  • imshow(I)

55
MATLAB 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

56
Binary images
57
Intensity Images
58
RGB images
59
Histogram Equalization
  • Histogram distribution of intensities
  • figure, imhist(I)
  • Equalize Image (contrast)
  • I2 histeq(I)
  • figure, imshow(I2)
  • figure, imhist(I2)

60
Histogram Equalization (cont.)
61
Histogram Equalization (cont.)
62
Write the Image
  • Validates the extension
  • Writes the image to disk
  • imwrite(I2, pout2.png)
  • imwrite(I2, pout2.png, BitDepth, 4)

63
Morphological 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)

64
Morphological Opening (cont.)
65
Subtract Images
  • Create a more uniform background
  • I2 imsubtract(I, background)
  • figure, imshow(I2)

66
Adjust the Image Contrast
  • stretchlim computes low hight to be mapped into
    bottom top
  • I3 imadjust(I2, stretchlim(I2), 0 1)
  • figure, imshow(I3)

67
Apply 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)

68
Apply Thresholding to the Image (cont.)
69
Labeling 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())

70
Select 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)

71
Object 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

72
Statistical 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)

73
Statistical Properties of Objects (cont.)
74
Storage 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)

75
Image 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)

76
Converting Image Types
  • dither
  • gray2ind
  • grayslice
  • im2bw
  • ind2gray
  • ind2rgb
  • mat2gray
  • rgb2gray
  • rgb2ind

77
Image Arithmetic
  • imabsdiff
  • imadd
  • imcomplement
  • imdivide
  • imlincomb
  • immultiply
  • imsubtract

78
Adding 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)

79
Adding Images (cont.)
80
Adding Images (cont.)
81
Subtracting 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

82
Subtracting Images (cont.)
83
Multiplying 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)

84
Multiplying Images (cont.)
85
Dividing 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)

86
Dividing Images (cont.)
87
Coordinate Systems
  • Pixel Coordinates
  • Discrete unit (integer)
  • (r, c)
  • ? (1, 1)
  • Spatial Coordinates
  • Continuous unit
  • (x, y)
  • ? (0.5, 0.5)

123
88
Non-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))

89
Spatial Transformations
  • Map pixel locations in an input image to new
    locations in an output image
  • Resizing
  • Rotation
  • Cropping

90
Resizing 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)

91
Resizing Images (cont.)
92
Rotating Images
  • Rotate an image by an angle in degrees
  • I imread(ic.tif)
  • J imrotate(I, 35, bilinear)
  • imshow(I)
  • figure, imshow(J)

93
Rotating Images (cont.)
94
Functions List
  • Functions List

95
Image Display
96
Image File I/O
97
Geometric Operations
98
Pixel Values and Statistics
99
Image Analysis
100
Image Enhancement
101
Linear Filtering
102
Image Transforms
103
Binary Image Operations
104
Color Space Conversions
105
Image Types and Type Conversions
106
Demos
Write a Comment
User Comments (0)
About PowerShow.com