Matlab Tutorial PDF
Matlab Tutorial PDF
Tutorial Course
1
Contents
1. Session One
What is Matlab?
MATLAB Parts
MATLAB Desktop
Matrices
Numerical Arrays
String Arrays
Elementary Math
Logical Operators
Math Functions
Polynomials and Interpolation
2 Importing and Exporting Data
Contents Continued
Graphics Fundamentals
2D plotting
Subplots
3D plotting
Specialized Plotting
Editing and Debugging M-files
2. Session Two
Script and Function Files
Basic Parts of an M-file
Flow Control Statements
M-file Programming
3
Contents Continued
Data types
Multidimensional Arrays
Structures
Cell Arrays
Nonlinear Numerical Functions
Ordinary Differential Equations (ODE)
Handle Graphics
Graphic Objects
Graphical User Interface (GUI)
4
What is MATLAB?
high-performance software
Computation
Visualization
Easy-to-use environment.
high-level language
Data types
Functions
Control flow statements
Input/output
Graphics
Object-oriented programming capabilities
5
MATLAB Parts
Developed Environment
Programming Language
Graphics
Toolboxes
Application Program Interface
6
Toolboxes
Collections of functions to solve problems of
several applications.
DSP Toolbox
Image Toolbox
Wavelet Toolbox
Neural Network Toolbox
Fuzzy Logic Toolbox
Control Toolbox
Communication Toolbox
7
MATLAB Desktop Tools
Command Window
Command History
Help Browser
Workspace Browser
Editor/Debugger
Launch Pad
8
Calculations at the Command
Line
MATLAB as a calculator Assigning Variables
» -5/(4.8+5.32)^2 » a = 2; Semicolon
ans = suppresses
» b = 5;
-0.0488 screen output
» (3+4i)*(3-4i) » a^b
ans = ans = Results
25 32 assigned to
» cos(pi/2) » x = 5/2*pi; “ans” if name
ans = not specified
» y = sin(x)
6.1230e-017
y =
» exp(acos(0.3))
ans = 1
3.5470 » z = asin(y) () parentheses for
z = function inputs
1.5708
12
Entering Numeric Arrays
» a=[1 2;3 4]
a = Use square
1 2 brackets [ ]
3 4
Row separator » b=[-2.8, sqrt(-7), (3+5+6)*3/4]
semicolon (;) b =
-2.8000 0 + 2.6458i 10.5000
Column separator » b(2,5) = 23
space / comma (,) b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
15
Numerical Array
Concatenation
Use [ ] to combine » a=[1 2;3 4]
existing arrays as a = Use square
matrix “elements” 1 2 brackets [ ]
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
Row separator: cat_a =
semicolon (;) 1 2 2 4
3 4 6 8
Column separator: 3 6 4 8
4*a
space / comma (,) 9 12 12 16
5 10 6 12
15 20 18 24
Note:
16 The resulting matrix must be rectangular
Deleting Rows and Columns
» 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.
17
Array Subscripting / Indexing
1 2 3 4 5
A= 4
1
10
6
1
11
6
16
2
21
1
2
2 8 1.2 7 9 12 4 17
25 22
A(1:5,5) A(1:end,end)
3 7.2 3 5 8
7 13 1 18
11 23 A(:,5) A(:,end)
A(21:25) A(21:end)’
A(3,1) 4 0 4
0.5 9 4 14 5 19
56 24
A(3) 5
5 23 83 10 1315 0 20
10 25
A(4:5,2:3)
A([9 14;10 15])
18
Matrix Multiplication
» a = [1 2 3 4; 5 6 7 8]; [2x4]
» b = ones(4,3); [4x3]
» c = a*b [2x4]*[4x3] [2x3]
c =
10 10 10
26 26 26 a(2nd row).b(3rd column)
Array Multiplication
» 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)
19
Matrix Manipulation Functions
• zeros: Create an array of all zeros
• ones: Create an array of all ones
• eye: Identity Matrix
• rand: Uniformly distributed random numbers
• diag: Diagonal matrices and diagonal of a matrix
• size: Return array dimensions
• fliplr: Flip matrices left-right
• flipud: Flip matrices up and down
• repmat: Replicate and tile a matrix
20
Matrix Manipulation Functions
• transpose (’): Transpose matrix
• rot90: rotate matrix 90
• tril: Lower triangular part of a matrix
• triu: Upper triangular part of a matrix
• cross: Vector cross product
• dot: Vector dot product
• det: Matrix determinant
• inv: Matrix inverse
• eig: Evaluate eigenvalues and eigenvectors
21
• rank: Rank of matrix
Character Arrays (Strings)
Created using single quote delimiter (')
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
24
Elementary Math
Logical Operators
Math Functions
25
Logical Operations
= = equal to »
Mass = [-2 10 NaN 30 -11 Inf 31];
»
each_pos = Mass>=0
> greater than
each_pos =
< less than 0 1 0 1 0 1 1
» all_pos = all(Mass>=0)
>= Greater or equal all_pos =
<= less or equal 0
» all_pos = any(Mass>=0)
~ not all_pos =
1
& and
» pos_fin = (Mass>=0)&(isfinite(Mass))
| or pos_fin =
0 1 0 1 0 0 1
isfinite(), etc. . . .
all(), any() Note:
• 1 = TRUE
find
• 0 = FALSE
26
Elementary Math Function
• abs, sign: Absolute value and Signum
Function
• sin, cos, asin, acos…: Triangular functions
• exp, log, log10: Exponential, Natural and
Common (base 10) logarithm
• ceil, floor: Round toward infinities
• fix: Round toward zero
27
Elementary Math Function
round: Round to the nearest integer
gcd: Greatest common devisor
lcm: Least common multiple
sqrt: Square root function
real, imag: Real and Image part of
complex
rem: Remainder after division
Elementary Math Function
• max, min: Maximum and Minimum of arrays
• mean, median: Average and Median of arrays
• std, var: Standard deviation and variance
• sort: Sort elements in ascending order
• sum, prod: Summation & Product of Elements
• trapz: Trapezoidal numerical integration
• cumsum, cumprod: Cumulative sum, product
• diff, gradient: Differences and Numerical
Gradient
28
Polynomials and
Interpolation
Polynomials
Representing
Roots (>> roots)
Evaluation (>> polyval)
Derivatives (>> polyder)
Curve Fitting (>> polyfit)
Partial Fraction Expansion (residue)
Interpolation
One-Dimensional (interp1)
Two-Dimensional (interp2)
29
Example
polysam=[1 0 0 8];
roots(polysam)
ans =
-2.0000
1.0000 + 1.7321i
1.0000 - 1.7321i
Polyval(polysam,[0 1 2.5 4 6.5])
ans =
8.0000 9.0000 23.6250 72.0000 282.6250
polyder(polysam)
ans =
3 0 0
[r p k]=residue(polysam,[1 2 1])
r = 3 7
p = -1 -1
k = 1 -2
30
Example
x = [0: 0.1: 2.5];
y = erf(x);
p = polyfit(x,y,6)
p =
0.0084 -0.0983 0.4217 -0.7435 0.1471 1.1064 0.0004
31
Importing and Exporting
Data
Using the Import Wizard
32
Input/Output for Text File
33
Input/Output for Binary File
fopen: Open a file for input/output
fclose: Close one or more open files
fread: Read binary data from file
fwrite: Write binary data to a file
fseek: Set file position indicator
» fid= fopen('mydata.bin' , 'wb');
» fwrite (fid,eye(5) , 'int32');
» fclose (fid);
» fid= fopen('mydata.bin' , 'rb');
» M= fread(fid, [5 5], 'int32')
» fclose (fid);
34
Graphics
Fundamentals
35
Graphics
Basic Plotting
plot, title, xlabel, grid,
legend, hold, axis
Editing Plots
Property Editor
Mesh and Surface Plots
meshgrid, mesh, surf,
colorbar, patch, hidden
Handle Graphics
36
2-D Plotting
Syntax:
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
Example:
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
plot(x,y,x,z,'linewidth',2)
title('Sample Plot','fontsize',14);
xlabel('X values','fontsize',14);
ylabel('Y values','fontsize',14);
legend('Y data','Z data')
grid on
37
Sample Plot
Title
Ylabel
Grid
Legend
Xlabel
38
Subplots
Syntax: subplot(rows,cols,index)
»subplot(2,2,1);
» …
»subplot(2,2,2)
» ...
»subplot(2,2,3)
» ...
»subplot(2,2,4)
» ...
39
Surface Plot Example
x = 0:0.1:2;
y = 0:0.1:2;
[xx, yy] = meshgrid(x,y);
zz=sin(xx.^2+yy.^2);
surf(xx,yy,zz)
xlabel('X axes')
ylabel('Y axes')
40
3-D Surface Plotting
contourf-colorbar-plot3-waterfall-contour3-mesh-surf
41
Specialized Plotting Routines
bar-bar3h-hist-area-pie3-rose
42
Editing and Debugging M-
Files
What is an M-File?
The Editor/Debugger
Search Path
Debugging M-Files
Types of Errors (Syntax Error and Runtime
Error)
Using keyboard and “ ; ” statement
Setting Breakpoints
Stepping Through
Continue, Go Until Cursor, Step, Step In, Step Out
Examining Values
Selecting the Workspace
Viewing Datatips in the Editor/Debugger
Evaluating a Selection
43
Debugging
Select
Workspace
Set Auto-
Breakpoints
tips
44
Programming and
Application
Development
45
Script and Function Files
• Script Files
• Work as though you typed commands into
MATLAB prompt
• Variable are stored in MATLAB workspace
• Function Files
• Let you make your own MATLAB Functions
• All variables within a function are local
• All information must be passed to functions as
parameters
46 • Subfunctions are supported
Basic Parts of a Function M-File
Output Arguments Function Name Input Arguments
47
Flow Control Statements
if Statement
if ((attendance >= 0.90) & (grade_average >= 60))
pass = 1;
end;
while Loops
eps = 1;
while (1+eps) > 1
eps = eps/2;
end
eps = eps*2
48
Flow Control Statements
for Loop
a = zeros(k,k) % Preallocate matrix
for m = 1:k
for n = 1:k
a(m,n) = 1/(m+n -1);
end
end
switch Statement
method = 'Bilinear';
switch lower(method)
case {'linear','bilinear'}
disp('Method is linear')
case 'cubic'
disp('Method is cubic')
otherwise
disp('Unknown method.')
end
Method is linear
49
M-file Programming Features
SubFunctions
Varying number of input/output arguments
Local and Global Variables
Obtaining User Input
Prompting for Keyboard Input
Pausing During Execution
Errors and Warnings
Displaying error and warning Messages
Shell Escape Functions (! Operator)
Optimizing MATLAB Code
Vectorizing loops
Preallocating Arrays
50
Function M-file
function r = ourrank(X,tol)
% rank of a matrix Multiple Input Arguments
s = svd(X); use ( )
if (nargin == 1)
»r=ourrank(rand(5),.1);
tol = max(size(X)) * s(1)* eps;
end
r = sum(s > tol);
Numeric Arrays
Multidimensional Arrays
Structures and Cell Arrays
52
Multidimensional Arrays
The first references array dimension
1, the row.
» A = pascal(4);
The second references dimension 2, » A(:,:,2) = magic(4)
the column. A(:,:,1) =
The third references dimension 3, 1 1 1 1
The page. 1 2 3 4
1 0 0 0 1 3 6 10
0 1 0 0
1 4 10 20
0 0 1 0
0 0 0 1
A(:,:,2) =
16 2 3 13
0 0 0 0 Page N 5 11 10 8
16 20 30 130 0
5 110 100 80 0 9 7 6 12
1 1 1 1
1 2
9
3
70 60 120
4
0 4 14 15 1
1 3
4 14 15
6 10
1 » A(:,:,9) =
1 4 10 20 diag(ones(1,4));
53 Page 1
Structures
• Arrays with named data containers called fields.
» patient.name='John Doe';
» patient.billing = 127.00;
» patient.test= [79 75 73;
180 178 177.5;
220 210 205];
» A(1,1) = {[1 4 3;
0 5 8;
7 2 9]};
» A(1,2) = {'Anne Smith'};
» A(2,1) = {3+7i};
» A(2,2) = {-pi:pi/10:pi};
Use optimset
options to determine options
= optimset('param1',value1,...)
57 parameter.
Ordinary Differential
Equations
(Initial Value Problem)
An explicit ODE with initial value:
[initialtime finaltime]
function dydt=myfunc(t,y)
dydt=zeros(2,1);
dydt(1)=y(2);
dydt(2)=(1-y(1)^2)*y(2)-y(1);
» [t,y]=ode45('myfunc',[0 20],[2;0])
3
Note:
1
Figure
object
UIMenu
objects UIControl
Axes object
objects
Surface
object
Line
objects
Text
objects 61
Obtaining an Object‟s Handle
1. Upon Creation
h_line = plot(x_data, y_data, ...)
2. Utility Functions
What is the current object?
0 - root object handle • Last object created
• OR
gcf - current figure handle • Last object clicked
gca- current axis handle
gco- current object handle
3. FINDOBJ
h_obj = findobj(h_parent, 'Property', 'Value', ...)
65
Axes static text
Frames
Checkbox Slider
Edit text
Property Inspector
Result Figure
67
Conclusion
Matlab is a language of technical computing.
Matlab, a high performance software, a high-
level language
Matlab supports GUI, API, and …
Matlab Toolboxes best fits different applications
Matlab …
68
Getting more help
• Contact http://www.mathworks.com/support
• You can find more help and FAQ about
mathworks products on this page.
• Contact comp.soft-sys.matlab Newsgroup
• Using Google Groups Page to Access this page
http://groups.google.com/
69
?
70