Sunteți pe pagina 1din 90

Short

MATLAB
Tutorial

Covered by: Dan Negrut


University of Wisconsin, Madison
Before getting started…
Acknowledgement:
 Almost entirely, this tutorial compiled from bits of information gathered
from various internet sources
 It is available for download from SBEL website in PPT format for other to be
able to save, edit, and distribute as they see fit
 Please let me know of any mistakes you find
 email me at my lastname@wisc.edu

The right frame of mind:


 You will not be able to say at the end of workshop that you know
MATLAB but rather that you have been exposed to MATLAB (I don’t know
MATLAB myself, I’m just using it…)

 Use MATLAB’s “help”, this is your first stop


 Second stop: search the web for examples that come close to what you
need
 You learn how to use MATLAB by using it, that’s why the start might be slow
and at times frustrating
Contents – 1
1. First hour of workshop
 What is Matlab?
 MATLAB Components
 MATLAB Desktop
 Matrices
 Importing and Exporting Data
 Elementary math with MATLAB
Contents – 2
2. Second hour of workshop
 M-file Programming
 Functions vs. Scripts
 Variable Type/Scope
 Debugging MATLAB functions
 Flow control in MATLAB
 Other Tidbits
 Function minimization
 Root finding
 Solving ODE’s
 Graphics Fundamentals
 Data Types most likely won’t have time for it
What is MATLAB?
Integrated Development Environment
(IDE)

Programming Language

Collection of Toolboxes

Excellent Linear Algebra support


MATLAB as an IDE
Integrated development environment (IDE)
 Write your own code for computation
 Good visualization (plotting) tools
 Easy-to-use environment

 Command Window

 Command History

 Help Browser

 Workspace Browser

 Editor/Debugger
MATLAB Desktop Tools
MATLAB as Programming Language

High-level language
 Data types
 Functions
 Control flow statements
 Input/output
 Graphics
 Object-oriented programming capabilities
Toolboxes

Collections of functions to solve problems from


several application fields.
 DSP (Digital Signal Processing) Toolbox
 Image Toolbox
 Wavelet Toolbox
 Neural Network Toolbox
 Fuzzy Logic Toolbox
 Control Toolbox
 Multibody Simulation Toolbox
 And many many other… (Visit for instance
http://www.tech.plym.ac.uk/spmc/links/matlab/matlab_toolbo
x.html
, amazing number of toolboxes available: if you need
something, it’s out there somewhere available for download)
MATLAB for [Linear] Algebra
Calculations at the Command Line
MATLAB as a calculator Assigning Variables
»» -5/(4.8+5.32)^2
-5/(4.8+5.32)^2 »» aa == 2; Semicolon
2;
ans
ans == suppresses
»» bb == 5;
5;
-0.0488
-0.0488 screen output
»» (3+4i)*(3-4i) »» a^b
a^b
(3+4i)*(3-4i)
ans ans
ans ==
ans == Results
25
25 32
32 assigned to
»» cos(pi/2)
cos(pi/2) »» xx == 5/2*pi; “ans” if name
5/2*pi; not specified
ans
ans == »» yy == sin(x)
6.1230e-017 sin(x)
6.1230e-017 yy ==
»» exp(acos(0.3))
exp(acos(0.3))
ans 11
ans ==
3.5470
3.5470 »» zz == asin(y)
asin(y) () parentheses for
zz == function inputs
1.5708
1.5708
A Note about Workspace:
Numbers stored in double-precision floating point format
General Functions

whos: List current variables and their size


clear: Clear variables and functions from memory
cd: Change current working directory
dir: List files in directory
pwd: Tells you the current directory you work in
echo: Echo commands in M-files
format: Set output format (long, short, etc.)
diary(foo): Saves all the commands you type in in a
file in the current directory called “foo”
Getting help
help command (>>help)
lookfor command (>>lookfor)
Help Browser (>>doc)
helpwin command (>>helpwin)

Search Engine
Printable Documents
 “Matlabroot\help\pdf_doc\”
Link to The MathWorks
Handling
Matrices in
Matlab
Matrices
Entering and Generating Matrices
Subscripts
Scalar Expansion
Concatenation
Deleting Rows and Columns
Array Extraction
Matrix and Array Multiplication

NOTE: we don’t have time to carefully look at all


these topics. I want you to be aware that these
facilities exist in MATLAB, and that you can access
them when needed by first doing a “help” on that
command
Entering Numeric Arrays
»» a=[1
a=[1 2;3
2;3 4]
4]
aa == Use square
11 22 brackets [ ]
33 44
NOTE: »» b=[-2.8,
b=[-2.8, sqrt(-7),
sqrt(-7), (3+5+6)*3/4]
(3+5+6)*3/4]
1) Row separator bb ==
semicolon (;)
-2.8000
-2.8000 00 ++ 2.6458i
2.6458i 10.5000
10.5000
»» b(2,5)
b(2,5) == 23
2) Column separator 23
space OR comma (,) bb ==
-2.8000
-2.8000 00 ++ 2.6458i
2.6458i 10.5000
10.5000 00 00
00 00 00 00 23.0000
23.0000

•Any MATLAB expression can be entered as a matrix


element (internally, it is regarded as such)
•In MATLAB, the arrays are always rectangular
The Matrix in MATLAB
Columns
(n)
1 2 3 4 5
A= 4
1
10
6
1
11
6
16
2
21
A (2,4)
1
2 7 12 17 22
2 8 1.2 9 4 25

Rows (m) 3 7.2 3 5 8


7 13
1 18
11 23 A (17)
4 0 4
0.5 9 4 14
5 19
56 24
5 10 15 20 25
5 23 83 13 0 10 Rectangular Matrix:
Scalar: 1-by-1 array
Vector: m-by-1 array
1-by-n array
Matrix: m-by-n array
Entering Numeric Arrays
Scalar expansion »» w=[1
w=[1 2;3
2;3 4]
4] ++ 55
ww ==
66 77
88 99
Creating »» xx == 1:5
1:5
sequences: xx ==
colon operator (:) 11 22 33 44 55
»» yy == 2:-0.5:0
2:-0.5:0
yy ==
2.0000
2.0000 1.5000
1.5000 1.0000
1.0000 0.5000
0.5000 00
»» zz == rand(2,4)
rand(2,4)
Utility functions for
zz ==
creating matrices.
0.9501
0.9501 0.6068
0.6068 0.8913
0.8913 0.4565
0.4565
0.2311
0.2311 0.4860
0.4860 0.7621
0.7621 0.0185
0.0185
Numerical Array Concatenation
(Tiling)

Use [ ] to combine »» a=[1


a=[1 2;3
2;3 4]
4]
existing arrays as aa == Use square
matrix “elements” 11 22
brackets [ ]
33 44
»» cat_a=[a,
cat_a=[a, 2*a;
2*a; 3*a,
3*a, 4*a;
4*a; 5*a,
5*a, 6*a]
6*a]
Row separator:
cat_a
cat_a ==
semicolon (;) 11 22 22 44
33 44 66 88
Column separator: 33 66 44 88 4*a
space / comma (,) 99 12
12 12
12 16
16
55 10
10 66 12
12
15
15 20
20 18
18 24
24

Note:
The resulting matrix must be rectangular
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 10 15 20 25
5 23 83 13 0 10
A(4:5,2:3)
A([9 14;10 15])
Deleting Rows and Columns

»» A=[1
A=[1 55 9;4
9;4 33 2.5;
2.5; 0.1
0.1 10
10 3i+1]
3i+1]
AA ==
1.0000
1.0000 5.0000
5.0000 9.0000
9.0000
4.0000
4.0000 3.0000
3.0000 2.5000
2.5000
0.1000
0.1000 10.0000
10.0000 1.0000+3.0000i
1.0000+3.0000i
»» A(:,2)=[]
A(:,2)=[]
AA == “:” is a VERY important construct in MATLAB
1.0000
1.0000 9.0000
9.0000
4.0000
4.0000 2.5000
2.5000
0.1000
0.1000 1.0000
1.0000 ++ 3.0000i
3.0000i
»» A(2,2)=[]
A(2,2)=[]
???
??? Indexed
Indexed empty
empty matrix
matrix assignment
assignment is
is not
not allowed.
allowed.
Matrix Multiplication
»» aa == [1
[1 22 33 4;
4; 55 66 77 8];
8]; [2x4]
»» bb == ones(4,3);
ones(4,3); [4x3]
»» cc == a*b
a*b [2x4]*[4x3] [2x3]
cc ==
10
10 10
10 10
10
26
26 26
26 26
26 a(2nd row).b(3rd column)

Array Multiplication (componentwise operation)


»» aa == [1
[1 22 33 4;
4; 55 66 77 8];
8];
»» bb == [1:4;
[1:4; 1:4];
1:4];
»» cc == a.*b
a.*b
cc ==
11 44 99 16
16
55 12
12 21
21 32
32 c(2,4) = a(2,4)*b(2,4)
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
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
• rank: Rank of matrix
Exercise 1 (10 minutes)
Define a matrix A of dimension 2 by 4 whose (i,j) entry is
A(i,j)=i+j
Extract two 2 by 2 matrices A1 and A2 out of the matrix A.
A1 contains the first two columns of A, A2 contains the last
two columns of A
Compute the matrix B to be the sum of A1 and A2
Compute the eigenvalues and eigenvectors of B
Solve the linear system Bx=b, where b has all the entries
equal to 1
Compute the determinant of B
Compute the inverse of B
Compute the condition number of B
NOTE: Use only MATLAB native functions for all operations
Elementary Math
Elementary Math

Logical Operators

Math Functions

Polynomial and Interpolation


Logical Operations

= = equal to »» Mass
Mass == [-2
[-2 10
10 NaN
NaN 30
30 -11
-11 Inf
Inf 31];
31];
»» each_pos
each_pos == Mass>=0
Mass>=0
> greater than
each_pos
each_pos ==
< less than 00 11 00 11 00 11 11
»» all_pos
all_pos == all(Mass>=0)
all(Mass>=0)
>= Greater or equal all_pos
all_pos ==
<= less or equal 00
»» all_pos
all_pos == any(Mass>=0)
any(Mass>=0)
~ not all_pos
all_pos ==
11
& and
»» pos_fin
pos_fin == (Mass>=0)&(isfinite(Mass))
(Mass>=0)&(isfinite(Mass))
| or pos_fin
pos_fin ==
00 11 00 11 00 00 11
isfinite(), etc. . . .
all(), any() Note:
• 1 = TRUE
find
• 0 = FALSE
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 to integer, toward +/-infinity
• fix: Round to integer, toward zero
Elementary Math Function
round: Round to the nearest integer
gcd: Greatest common divisor
lcm: Least common multiple
sqrt: Square root function
real, imag: Real and Image part of
complex
rem: Remainder after division
Elementary Math Function
Operating on Arrays
• 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
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)
Example
polysam=[1
polysam=[1 00 00 8];
8];
roots(polysam)
roots(polysam)
ans
ans ==
-2.0000
-2.0000
1.0000
1.0000 ++ 1.7321i
1.7321i
1.0000
1.0000 -- 1.7321i
1.7321i
polyval(polysam,[0
polyval(polysam,[0 11 2.5
2.5 44 6.5])
6.5])
ans
ans ==
8.0000
8.0000 9.0000
9.0000 23.6250
23.6250 72.0000
72.0000 282.6250
282.6250
polyder(polysam)
polyder(polysam)
ans
ans ==
33 00 00
[r
[r pp k]=residue(polysam,[1
k]=residue(polysam,[1 44 3])
3])
rr == 9.59.5 3.5
3.5
pp == -3
-3 -1
-1
kk == 11 -4
-4
Curve fitting
polyfit(X,Y,N) - finds the
coefficients of a polynomial
P(X) of degree N that over the
points X fits the data Y best in
a least-squares sense

xx == [0:
[0: 0.1:
0.1: 2.5];
2.5];
yy == erf(x);
erf(x);
pp == polyfit(x,y,6)
polyfit(x,y,6)
pp ==
0.0084
0.0084 -0.0983
-0.0983 0.4217
0.4217 -0.7435
-0.7435 0.1471
0.1471 1.1064
1.1064 0.0004
0.0004

interp1(x,y,[0.45
interp1(x,y,[0.45 0.95
0.95 2.2
2.2 3.0])
3.0])
ans =
ans =
0.4744
0.4744 0.8198
0.8198 0.9981
0.9981 NaN
NaN
Exercise 2 (10 minutes)
Let x be an array of values from 0 to 2, equally
spaced by 0.01
 Compute the array of exponentials corresponding to
the values stored in x
 Find the polynomial p of degree 5 that is the best
least square approximation to y on the given interval
[0,2]
 Evaluate the polynomial p at the values of x, and
compute the error z with respect to the array y
 Interpolate the (x,z) data to approximate the value of
the error in interpolation at the point .9995
END
MATLAB for [Linear] Algebra
Programming
and
Application
Development
Topics discussed…
The concept of m-file in MATLAB

Script versus function files

The concept of workspace

Variables in MATLAB
 Type of a variable
 Scope of a variable

Flow control in MATLAB

The Editor/Debugger
Before Getting Lost in Details…

Obtaining User Input


 “input” - Prompting the user for input
>> apls = input( ‘How many apples? ‘ )

 “keyboard” - Pausing During Execution (when in M-file)

Shell Escape Functions (! Operator)

Optimizing MATLAB Code


 Vectorizing loops
 Preallocating Arrays
Function M-file
function
function rr == ourrank(X,tol)
ourrank(X,tol)
%% rank
rank ofof aa matrix
matrix Multiple Input Arguments
ss == svd(X);
svd(X); use ( )
if
if (nargin
(nargin ==== 1)
1) »r=ourrank(rand(5),.1);
tol
tol == max(size(X))
max(size(X)) ** s(1)*
s(1)* eps;
eps;
end
end
rr == sum(s
sum(s >> tol);
tol);

function
function [mean,stdev]
[mean,stdev] == ourstat(x)
ourstat(x)
[m,n]
[m,n] == size(x);
size(x);
Multiple Output
if
if mm ==
== 11
Arguments, use [ ]
m = n;
»[m std]=ourstat(1:9); endm = n;
end
mean
mean == sum(x)/m;
sum(x)/m;
stdev
stdev == sqrt(sum(x.^2)/m
sqrt(sum(x.^2)/m –– mean.^2);
mean.^2);
Basic Parts of a Function M-File
Output Arguments Function Name Input Arguments

Online Help 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
Function Code
m = n;
end
y = sum(x)/m;
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
• Subfunctions are supported
The concept of Workspace
• At any time in a MATLAB session, the code has a workspace
associated with it
• The workspace is like a sandbox in which you find yourself at a
certain point of executing MATLAB
• The “Base Workspace”: the workspace in which you live when
you execute commands from prompt
• Remarks:
• Each MATLAB function has its own workspace (its own
sandbox)
• A function invoked from a calling function has its own and
separate workspace (sandbox)
• A script does not lead to a new workspace (unlike a function),
but lives in the workspace from which it was invoked
Variable Types in MATLAB
• Local Variables
• In general, a variable in MATLAB has local scope, that is, it’s only
available in its workspace
• The variable disappears when the workspace ceases to exist
• Recall that a script does not define a new workspace – be careful,
otherwise you can step on variables defined at the level where the
script is invoked
• Since a function defines its own workspace, a variable defined in a
function is local to that function
• Variables defined outside the function should be passed to function
as arguments. Furthermore, the arguments are passed by value
• Every variable defined in the subroutine, if to be used outside the
body of the function, should be returned back to the calling
workspace
Variable Types in MATLAB
• Global Variables
• These are variables that are available in multiple workspaces
• They have to be explicitly declared as being global
• Not going to expand on this, since using global variables is a bad
programming practice

• A note on returning values from a function


• Since all variables are local and input arguments are passed by value,
when returning from a function a variable that is modified inside that
function will not appear as modified in the calling workspace unless
the variable is either global, or declared a return variable for that
function
Flow Control Statements
if Statement
if
if ((attendance
((attendance >=
>= 0.90)
0.90) && (grade_average
(grade_average >=
>= 60))
60))
pass
pass == 1;
1;
end;
end;

while Loops
eps
eps == 1;
1;
while
while (1+eps)
(1+eps) >> 11
eps
eps == eps/2;
eps/2;
end
end
eps
eps
Flow Control Statements
aa == zeros(k,k)
zeros(k,k) %% Preallocate
Preallocate matrix
matrix
for
for mm == 1:k
1:k

for Loop: for


for nn == 1:k
a(m,n)
1:k
a(m,n) == 1/(m+n
1/(m+n -1);
-1);
end
end
end
end

method
method == 'Bilinear';
'Bilinear';
...
... (some
(some code
code here)...
here)...
switch
switch lower(method)
lower(method)
case
case {'linear','bilinear'}
{'linear','bilinear'}
disp('Method
disp('Method is
is linear')
switch case
case 'cubic'
'cubic'
linear')

Statement: disp('Method
disp('Method is
otherwise
otherwise
is cubic')
cubic')

disp('Unknown
disp('Unknown method.')
method.')
end
end
Method
Method is
is linear
linear
Editing and Debugging M-Files
The Editor/Debugger

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
Debugging
Select
Workspace
Set Auto-
Breakpoints

tips
Importing and Exporting Data
Using the Import Wizard

Using Save and Load command

save
save fname
fname load
load fname
fname
save
save fname
fname xx yy zz load
load fname
fname xx yy zz
save
save fname
fname -ascii
-ascii load
load fname
fname -ascii
-ascii
save
save fname
fname -mat
-mat load
load fname
fname -mat
-mat
Input/Output for Text File

•Read formatted data, reusing the


format string N times.
»»[A1…An]=textread(filename,format,N)
[A1…An]=textread(filename,format,N)

Suppose the text file stars.dat contains data in the following form:
Jack Nicholson 71 No Yes 1.77
Helen Hunt 45 No No 1.73

Read each column into a variable


[firstname, lastname, age, married, kids, height] = textread('stars.dat','%s%s%d%s%s%f');

•Import and Exporting Numeric Data


with General ASCII delimited files
»» MM == dlmread(filename,delimiter,range)
dlmread(filename,delimiter,range)
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');
fid= fopen('mydata.bin' 'wb');
»» fwrite (fid,eye(5) , 'int32');
fwrite (fid,eye(5) , 'int32');
»» fclose
fclose (fid);
(fid);
»» fid=
fid= fopen('mydata.bin',, 'rb');
fopen('mydata.bin' 'rb');
»» M= fread(fid, [5 5], 'int32')
M= fread(fid, [5 5], 'int32')
»» fclose
fclose (fid);
(fid);
Exercise 3: A debug session
(10 minutes)
Use the function demoBisect provided on the
next slide to run a debug session
 Save the MATLAB function to a file called
demoBisect.m in the current directory
 Call once the demoBisect.m from the MATLAB

prompt to see how it works


>>help demoBisect
>>demoBisect(0, 5, 30)
 Place some breakpoints and run a debug session

 Step through the code, and check the values of variables


 Use the MATLAB prompt to echo variables
 Use dbstep, dbcont, dbquit commands
function xm = demoBisect(xleft,xright,n)
% demoBisect Use bisection to find the root of x - x^(1/3) - 2
%
% Synopsis: x = demoBisect(xleft,xright)
% x = demoBisect(xleft,xright,n)
%
% Input: xleft,xright = left and right brackets of the root
% n = (optional) number of iterations; default: n = 15
%
% Output: x = estimate of the root

if nargin<3, n=15; end % Default number of iterations


a = xleft; b = xright; % Copy original bracket to local variables
fa = a - a^(1/3) - 2; % Initial values of f(a) and f(b)
fb = b - b^(1/3) - 2;
fprintf(' k a xmid b f(xmid)\n');

for k=1:n
xm = a + 0.5*(b-a); % Minimize roundoff in computing the midpoint
fm = xm - xm^(1/3) - 2; % f(x) at midpoint
fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n',k,a,xm,b,fm);
if sign(fm)==sign(fa) % Root lies in interval [xm,b], replace a
a = xm;
fa = fm;
else % Root lies in interval [a,xm], replace b
b = xm;
fb = fm;
end
end
Other Tidbits
The “inline” Utility
• inline function »» ff ==
inline('3*sin(2*x.^2)','x')
inline('3*sin(2*x.^2)','x')
ff ==
Use char function Inline
Inline function:
function:
to convert inline f(x)
f(x) == 3*sin(2*x.^2)
3*sin(2*x.^2)
object to string »» f(2)
f(2)
ans
ans ==
2.9681
2.9681
• Numerical Integration using quad
»» QQ == quad('1./(x.^3-2*x-5)',0,2);
quad('1./(x.^3-2*x-5)',0,2);
»» FF == inline('1./(x.^3-2*x-5)');
inline('1./(x.^3-2*x-5)');
»» QQ == quad(F,0,2);
quad(F,0,2);
»» QQ == quad('myfun',0,2)
quad('myfun',0,2)
Note:
quad function use adaptive function y = myfun(x)

Simpson quadrature y = 1./(x.^3-2*x-5);


Root Finding, Optimization…
fzero finds a zero of a single variable function
[x,fval]= fzero(fun,x0,options)
 fun is inline function or m-function
fminbnd minimize a single variable function on a
fixed interval. x1<x<x2
[x,fval]= fminbnd(fun,x1,x2,options)

fminsearch minimize function w/ several variables


[x,fval]= fminsearch(fun,x0,options)

Use optimset to determine options parameter.


options = optimset('param1',value1,...)
Ordinary Differential Equations
(Solving Initial Value Problem)

An explicit ODE with initial value:

Using ode45 for non-stiff functions and ode23t


for stiff functions.
[t,y] = solver(odefun,tspan,y0,options)
function dydt = odefun(t,y) Initialvlue

[initialtime finaltime]

•Use odeset to define options parameter


ODE Example:

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
[t,y]=ode45('myfunc',[0 20],[2;0])
20],[2;0])
3

Note:
1

Help on odeset to set options


0

for more accuracy and other


-1

useful utilities like drawing


-2

results during solving.


-3
0 2 4 6 8 10 12 14 16 18 20
Example 4: Using ODE45
(5 minutes)

Use the example on the previous page


to solve the slightly different IVP on the
interval [0,20] seconds:

y1  (1  0.9 y12 ) y1  y1  0


y1 (0)  2
y1 (0)  0
Graphics
Fundamentals
Graphics and Plotting in MATLAB
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
2-D Plotting
color line marker
Syntax:
plot(x1,
plot(x1, y1,
y1, 'clm1',
'clm1', x2,
x2, y2,
y2, 'clm2',
'clm2', ...)
...)

Example:
x=[0:0.1:2*pi];
x=[0:0.1:2*pi];
y=sin(x);
y=sin(x);
z=cos(x);
z=cos(x);
plot(x,y,x,z,'linewidth',2)
plot(x,y,x,z,'linewidth',2)
title('Sample
title('Sample Plot','fontsize',14);
Plot','fontsize',14);
xlabel('X
xlabel('X values','fontsize',14);
values','fontsize',14);
ylabel('Y
ylabel('Y values','fontsize',14);
values','fontsize',14);
legend('Y
legend('Y data','Z
data','Z data')
data')
grid
grid on
on
Sample Plot
Title

Ylabel
Grid

Legend

Xlabel
Displaying Multiple Plots
Nomenclature:
 Figure window – the window in which MATLAB displays plots
 Plot – a region of a window in which a curve (or surface) is
displayed

Three typical ways to display multiple curves in MATLAB


(other combinations are possible…)
 One figure contains one plot that contains multiple curves
 Requires the use of the command “hold” (see MATLAB help)
 One figure contains multiple plots, each plot containing one curve
 Requires the use of the command “subplot”
 Multiple figures, each containing one or more plots, each
containing one or more curves
 Requires the use of the command “figure” and possibly “subplot”
Subplots
Syntax: subplot(rows,cols,index)
subplot(rows,cols,index)

»»subplot(2,2,1);
subplot(2,2,1);
»» ……

»»subplot(2,2,2)
subplot(2,2,2)
»» ...
...

»»subplot(2,2,3)
subplot(2,2,3)
»» ...
...

»»subplot(2,2,4)
subplot(2,2,4)
»» ...
...
The “figure” Command
Use if you want to have several figures open for plotting

The command by itself creates a new figure window and


returns its handle
>> figure

If you have 20 figures open and want to make figure 9


the default one (this is where the next plot command will
display a curve) do
>> figure(9)
>> plot(…)

Use the command close(9) if you want to close figure 9 in


case you don’t need it anymore
Surface Plot Example
xx == 0:0.1:2;
0:0.1:2;
yy == 0:0.1:2;
0:0.1:2;
[xx,
[xx, yy]
yy] == meshgrid(x,y);
meshgrid(x,y);
zz=sin(xx.^2+yy.^2);
zz=sin(xx.^2+yy.^2);
surf(xx,yy,zz)
surf(xx,yy,zz)
xlabel('X
xlabel('X axes')
axes')
ylabel('Y axes')
ylabel('Y axes')
3-D Surface Plotting
contourf-colorbar-plot3-waterfall-contour3-mesh-surf
Specialized Plotting Routines
bar-bar3h-hist-area-pie3-rose
Advanced
Topics
Handle Graphics
Graphics in MATLAB consist of objects:
 root, figure, axes, image, line, patch,
rectangle, surface, text, light
Creating Objects
Setting Object Properties Upon
Creation
Obtaining an Object’s Handles
Knowing Object Properties
Modifying Object Properties
 Using Command Line
 Using Property Editor
Graphics Objects
Root
object

Figure
object
UIMenu
objects UIControl
Axes object
objects

Surface
object

Line
objects

Text
objects
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. h_obj
FINDOBJ
= findobj(h_parent, 'Property', 'Value', ...)

Default = 0 (root object)


Modifying Object Properties
• Obtaining a list of current properties:
get(h_object)

• Obtaining a list of settable properties:


set(h_object)

• Modifying an object’s properties


 Using Command Line
set(h_object,'PropertyName','New_Value',...)

 Using Property Editor


Graphical User Interface

What is GUI?
What is figure and *.fig file?
Using guide command
GUI controls
GUI menus
Axes static text
Frames

Checkbox Slider

Edit text

Radio Buttons Push Buttons


Guide Editor

Property Inspector

Result Figure
Character String
Manipulation
Character Arrays (Strings)

»» str
str == 'Hi
'Hi there,'
there,'
str
str ==
Hi
Hi there,
there,
»» str2
str2 == 'Isn''t
'Isn''t MATLAB
MATLAB great?'
great?'
str2
str2 ==
Isn't
Isn't MATLAB
MATLAB great?
great?

str = H i t h e r e , 1x9 vector


String Array Concatenation
Using [ ] operator: »» str
str ='Hi
='Hi there,';
there,';
Each row must be »» str1='Everyone!'; 1x9 vectors
str1='Everyone!';
same length »» new_str=[str,
new_str=[str, '' ',', str1]
str1]
new_str
new_str ==
Row separator:
Hi
Hi there,
there, Everyone!
Everyone! vectors
1x19 vector
semicolon (;)
»» str2
str2 == 'Isn''t
'Isn''t MATLAB
MATLAB great?';
great?';
Column separator: »» new_str2=[new_str;
new_str2=[new_str; str2]
str2]
space / comma (,) new_str2
new_str2 ==
Hi
Hi there,
there, Everyone!
Everyone!
Isn't
Isn't MATLAB great?
MATLAB great? 2x19 matrix

For strings of different length:


• STRVCAT »» new_str3
new_str3 == strvcat(str,
strvcat(str, str2)
str2)
• char new_str3 2x19 matrix
new_str3 ==
Hi
Hi there,
there, (zero padded)
Isn't
Isn't MATLAB
MATLAB great?
great?
Working with String Arrays
String Comparisons
 strcmp: compare whole strings
 strncmp: compare first ‘N’ characters
 findstr: finds substring within a larger string

Converting between numeric & string arrays:


 num2str: convert from numeric to string array
 str2num: convert from string to numeric array
Data Types
Data Types

Numeric Arrays
Multidimensional Arrays
Structures and Cell Arrays
Multidimensional Arrays
The first references array dimension
1, the row.
»» AA == pascal(4);
pascal(4);
The second references dimension 2, » A(:,:,2) = magic(4)
» A(:,:,2) = magic(4)
the column. A(:,:,1)
A(:,:,1) ==
The third references dimension 3, 11 11 11 11
The page. 11 22 33 44
1 0 0 0 11 33 66 10
10
0 1 0 0
11 44 10
10 20
20
0 0 1 0
0 0 0 1 A(:,:,2)
A(:,:,2) ==
16
16 22 33 13
13
0 0 0 0 Page N
55 11
11 10
10 88
16 20 30 130 0
110 1
100 80 0 99 77 66 12
12
1 15 1
9 70 60 120 0
44 14 15 11
1 2 3 4 14 15
1 3
4 14 15
6 10
1
»» A(:,:,9)
A(:,:,9) ==
1 4 10 20 diag(ones(1,4));
diag(ones(1,4));
Page 1
Structures
•Arrays with named data containers called fields.
»» patient.name='John
patient.name='John Doe';
Doe';
»» patient.billing
patient.billing == 127.00;
127.00;
»» patient.test=
patient.test= [79
[79 75
75 73;
73;
180
180 178
178 177.5;
177.5;
220
220 210
210 205];
205];

•Also, Build structure arrays using the struct function.


•Array of structures
»» patient(2).name='Katty
patient(2).name='Katty Thomson';
Thomson';
»» Patient(2).billing
Patient(2).billing == 100.00;
100.00;
»» Patient(2).test=
Patient(2).test= [69
[69 25
25 33;
33; 120
120 128
128 177.5;
177.5; 220
220
210
210 205];
205];
Cell Arrays
•Array for which the elements are cells and can hold
other MATLAB arrays of different types.

»» A(1,1)
A(1,1) == {[1
{[1 44 3;
3;
00 55 8;
8;
77 22 9]};
9]};
»» A(1,2)
A(1,2) == {'Anne
{'Anne Smith'};
Smith'};
»» A(2,1)
A(2,1) == {3+7i};
{3+7i};
»» A(2,2)
A(2,2) == {-pi:pi/10:pi};
{-pi:pi/10:pi};

•Using braces {} to point to elements of cell array


•Using celldisp function to display cell array
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 …
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
• Use google to find more information (like the
content of this presentation, in the first place)
?

S-ar putea să vă placă și