Lec Matlab
Lec Matlab
Workspace /
Current Directory
Command
Window
Command
History
workspace
>> b=10;
>> c=a+b
c=
22
>>
Workspace (continued )
7
help
>> help whos % displays documentation for the
function whos
>> lookfor convert % displays functions with convert in the
first help line
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> 1:2:10
ans = Try the following
1 3 5 7 9 >> x=0:pi/12:2*pi;
>> y=sin(x)
The : operator and matrices
12
A=
>>A(3,2:3) 3 2 1
ans = 5 1 0
2 1 7
1 7
>>A(:,2)
ans =
2
1
Whatll happen if you type A(:,:) ?
1
Manipulating Matrices A=
3 2 1
5 1 0
13
2 1 7
Create matrices A and B and try out the the matrix operators in this slide
Scripts
14
Matlab editor
Use scripts to execute a series of
Matlab commands
Matlab
Desktop
Press to create
new m-file in the
matlab editor
Scripts (continued)
15
Scripts will manipulate
and store variables and
matrices in the Matlab
Workspace (memory).
They can be called from
the Matlab command line
by typing the (case Will be slightly
sensitive!) filename of the different in Linux
script file.
>> myscript
Scripts can be opened in
the editor by the following
>> open myscript
Highlight a few lines of your
script by left- clicking and
dragging the mouse over the
lines. Right-click the
highlighted lines and select
Evaluate Selection.
Basic Task: Plot the function
sin(x) between 0x4
Create an x-array of 100 samples between 0
and>>x=linspace(0,4*pi,100);
4.
0.8
0.6
0.4
0.2
-0.2
>>plot(y) -0.4
-0.6
-0.8
-1
0 10 20 30 40 50 60 70 80 90 100
Plot the function e-x/3sin(x)
between 0x4
Create an x-array of 100 samples between 0
and 4.
>>x=linspace(0,4*pi,100);
>>plot(y2) 0.6
0.5
0.4
0.3
0.2
0.1
-0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities
plot(.) 0.7
0.6
0.5
Example: 0.4
>>x=linspace(0,4*pi,100);
0.3
0.2
>>y=sin(x); 0.1
>>plot(y) -0.1
>>plot(x,y) -0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
stem(.) 0.7
0.6
Example:
0.5
0.4
>>stem(y) 0.3
0.2
>>stem(x,y) 0.1
-0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities
title(.)
>>title(This is the sinus function)
This is the sinus function
1
0.8
xlabel(.) 0.6
0.4
0.2
>>xlabel(x (secs))
sin(x)
0
-0.2
-0.4
ylabel(.) -0.6
-0.8
-1
0 10 20 30 40 50 60 70 80 90 100
>>ylabel(sin(x))
x (secs)
Operators (relational,
logical)
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than equal to
& And operator
| Or operator
Flow Control
if
for
while
break
.
Control Structures
If Statement Syntax
Some Dummy Examples
for m=13:-0.2:-21
Some Matlab Commands;
end
Dummy Example
while (condition)
Matlab Commandswhile ((a>3) & (b==5))
Some Matlab Commands;
end end
Use of M-File
Click to
create a new
M-File
Extension .m
A text file containing script or function or program to run
Use of M-File Save file as Test.m
Same Name
Writing User Defined Functions
Another function which takes an input array and returns the sum
and product of its elements as outputs
Programming in Matlab.
Users can write functions which can be called from the
command line.
Functions can accept input variable(s)/matrice(s) and will output
variable(s)/matrice(s).
Functions will not manipulate variable(s)/matrice(s) in the
Matlab Workspace.
In Matlab functions closely resemble scripts and can be written
in the Matlab editor. Matlab functions have the function
keyword.
Remember that the filename of a function will be its calling
function name.
Dont overload any built-in functions by using the same
filename for your functions or scripts!
Functions can be opened for editing using the open command.
Many built-in Matlab functions can also be viewed using this
command.
Functions (continued)
34
Without ; to
print output
i=
4
i=
16
i= Method is linear
256 >>
Debugging
36
Debug menus
Set breakpoints to stop the execution of code
>> [i j]=sort2(2,4)
K>>
K>> whos
Name Size Bytes Class
a 1x1 8 double array
b 1x1 8 double array
Grand total is 2 elements using 16 bytes
K>> a
a=
2
K>> return
i= local function
workspace
4 Click mouse on the left
j= of the line of code to
2
exit debug create a breakpoint
mode
Visualisation - plotting data
37
>> plot(t,y,b.-')
Investigate the function
>> y=A*cos(w*t+phi);
for different values of phi (eg: 0, pi/4, pi/3,
pi/2), w (eg: 1, 2, 3, 4) and A (eg: 1, 0.5, 2). Use
the hold on Matlab command to display your
plots in the same figure. Remember to type A = amplitude
hold off to go back to normal plotting mode. phi = phase
Try using different plot styles (help plot) w = angular frequency = 2*pi*frequency
38
3
Generating Vectors from
functions
zeros(M,N) MxN matrix of zeros x = zeros(1,3)
x =
0 0 0
Given:
A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers
or logicals.
A(4,2)
Error: ??? Index exceeds matrix dimensions.
41
Some Built-in functions
mean(A):mean value of a vector
max(A), min (A): maximum and minimum.
sum(A): summation.
sort(A): sorted vector
median(A): median value
std(A): standard deviation.
det(A) : determinant of a square matrix
dot(a,b): dot product of two vectors
Cross(a,b): cross product of two vectors
Inv(A): Inverse of a matrix A
Indexing Matrices
1:m ]
0.2311
A(1,2:3)=[0.6068 0.4231]
Adding Elements to a Vector or a
Matrix
>> A=1:3 >> C=[1 2; 3 4]
A= C=
1 2 3 1 2
>> A(4:6)=5:2:9 3 4
A= >> C(3,:)=[5 6];
1 2 3 5 7 9 C=
1 2
>> B=1:2 3 4
B= 5 6
1 2
>> B(5)=7; >> D=linspace(4,12,3);
B= >> E=[C D]
1 2 0 0 7 E=
1 2 4
3 4 8
5 6 12
Graphics - 2D Plots
plot(xdata, ydata, marker_style);
For example: Gives:
>> x=-5:0.1:5;
>> sqr=x.^2;
>> pl1=plot(x, sqr, 'r:s');
Graphics - Overlay Plots
Use hold on for overlaying graphs
So the following: Gives:
>> n=-10:10;
>> f=stem(n,cos(n*pi/4)) 0.5
>> title('cos(n\pi/4)')
>> xlabel('n') 0
-0.5
-1
-10 -5 0 5 10
n
subplots
Use subplots to divide a plotting
window into several panes.
Cosine Sine
1 1
0.8 0.8
>> x=0:0.1:10;
>> f=figure; 0.6 0.6
>> title('Cosine')
-0.2 -0.2
>> f2=subplot(1,2,2);
-0.4 -0.4
>> plot(x,sin(x),'d');
>> grid on; -0.6 -0.6
-1 -1
0 5 10 0 5 10
Save plots
Use saveas(h,'filename.ext') to save
a figure to a file.
x = 2:0.5:4; y=1:0.5:3;
[X,Y] = meshgrid(x,y);
x(t ) sin(3t ) 5 t 5
y (t ) e 2t 3 0t 5
Plot the following signals, use log scale for y-axis
x(t ) e t 2 (2t 1) 0 t 10
Plot the real part and imaginary part of the following signal
x(t ) e 0.5t j ( t / 3) 0 t 10
For the signal in previous question, plot its phase and magnitude
58
4
Simulink
Graphical block diagram capability
Can drag and drop components (called
blocks)
Real-time Workshop
Simulink
An environment for building and
simulating models.
Continuous, discrete or hybrid
systems
Linear and nonlinear components
AAtypical
typicalSimulink
Simulinkmodel
modelincludes
includesSources,
Sources,Systems
Systemsand
and
Sinks.
Sinks.
Scope
2
Gain1 1
0.9 Unit Delay
z
Simulink Block Libraries
Simulink contains block libraries, which contain
components that can be used to build models.
In1 Out1
Scope XY Graph
Sources Sinks Discrete Linear Nonlinear Connections
0
Blocksets & Simulink Block Library 2.2
Toolboxes Demos Display
Copyright (c) 1990-1998 by The MathWorks, Inc.
untitled.mat simout
To File To Workspace
components
Building a Simulink Model
11
Gain
Gain Sum
Sum
11 11
Sine Wave Sum ss s+1
s+1
Integrator
Integrator Transfer Fcn
Transfer Fcn
Model Window
x'x'==Ax+Bu
Ax+Bu (s-1)
(s-1)
yy==Cx+Du
Cx+Du s(s+1)
s(s+1)
State-Space
State-Space Zero-Pole
Zero-Pole
du/dt
du/dt
1
Constant Derivative
Derivative DotProduct
Dot Product
Signal Step
drag blocks
Generator Generator
untitled.mat
Digital Clock
[T,U]
Library
model From File From
Workspace
window
Random Uniform Random Band-Limited
Number Number White Noise
Sources Library
Connecting Blocks
1
You
You can
can specify
specify the
the appropriate
appropriate solver
solver that
that is
is
to
to be
be used.
used. For
For discrete-time
discrete-time systems
systems use
use
the
theFixed-step
Fixed-stepDiscrete
Discretesolver
solverififthere
thereis
isonly
onlyaasingle
single
sample
sampletime.
time.
The
TheVariable-step
Variable-stepDiscrete
Discretesolver
solverforformultirate
multirate
systems.
systems.
You
You can
can also
also specify
specify variables
variables that
that are
are to
to be
be
obtained
obtained from
from or
or returned
returned to
to the
the MATLAB
MATLAB
workspace.
workspace.
Subsystems
You can select portions of your model using the mouse and
make them into a subsystem.
In1
Out1
Filtered
My 1st order Signal
filter
1 B0
1
Function Zero-Order This figure demonstrates Original In1
Generator Hold Signal B0 Out1
a simple first order IIR filter Sum
1
In1
Out1 A1
z
Filtered A1 Unit Delay
My 1st order Signal
filter
Numerical methods
Solving Algebraic Equations
From linearity, it is easy to solve the
equation
3 x 7 12
f ( x) 0
f(x) Graph of f(x) versus x
roots of f
Iterative Methods
Iterative methods start with a guess,
labeled x0 and through easy
calculations, generate a sequence
x1, x2, x3,
Goal is that
lim xn x
n
sequence satisfies
f x 0
Absolute in f
Sometimes (in bisection, for example) we
can bound this, even without knowing x*.
|f(xn)| < tol
Bisection Method, basic idea
f xL 0
Suppose f is continuous, f xR 0
f xR
Intermediate value theorem
xL xM
f xL xR
graph of f(x)
x0 x
functions are equal at x0
h x0 f x0
slope of h (everywhere)
equals the slope of f at x0
h ' x f ' x0 for all x
graph of h is straight line
h x ax b for some a, b
h x f x0 f ' x0 x x0
Newtons Method:
motivation
Graph of h(x), the straight-line
approximation to f at x0
graph of f(x)
x0 x
h x f x0 f ' x0 x x0
Approximation to f, near x0
graph of f(x)
*
xapp x0 x
f xk
xk 1 xk '
f xk General form of the iteration
Newtons Method: iteration
f xk
xk 1 xk ' General form of the iteration
f xk
Facts about Newtons method to solve f(x) = 0
At each step, need to evaluate the function and its
derivative at a single point
Not guaranteed to converge. It might cycle, and it
might diverge.
If it does converge, the convergence is quadratic.
More complicated than bisection, can work better.
Generalizes to N equations in N unknowns
Function handles and feval
Several Matlab functions solve your problem by repeatedly
calling functions that you supply
finding zeros of a function (fzero) New data type: add to list
with double, cell, char,
Integrating a function (trapz, quad) struct.
Integrating a differential equation (ode45)
[out1,out2,] = feval(FuncH,arg1,arg2,)
f x f x h
The backwardf bdifference
x at x with stepsize h
h
(h>0) is
f x h f x h
f c x
2h
The centered difference at x with stepsize h
(h>0) is
Numerical Differentiation
yi yi 1
backward at xi
xi xi 1
yi 1 yi 1
centered at xi
xi 1 xi 1
What are we actually
computing?
Average values: If g is integrable, then the average value of g
over the interval [a,b] is defined as
g x dx
b
g[avg :
a
a ,b ]
ba
In other words, avg is the constant which satisfies
g [ a ,b ]
ie., the only constant
function which has the
same integral over
[a,b] as does g is the
g x dx b a g
b
avg constant function
[ a ,b ] whose value is
a avg
g [ a ,b ]
What are we actually
computing?
If f is differentiable, then
f x dx
a
f b f a
If ab, then
b
1 f (b) f (a)
f x dx
ba a ba
Average value of f over the interval (a,b)
What are we computing?
(contd)
Mean-Value Theorem: If f is
differentiable on (a,b)
continuous on [a,b]
then there is an y(a,b) such that
f b f a b a f y
What are we computing?
(contd)
This gives two interpretations of the finite-
f b f a
difference b
1
f x dx
ba ba a
Average value of f over the interval (a,b)
f b f a
f y for some y a, b
ba
exact value of f at some point in interval (a,b)
What are we computing?
(contd)
So, two interpretations of the finite-
difference
f x h f x
xh
1
f d
h h x
f x h f x
f y some y x, x h
h
Bounding the Errors
2nd derivative.
use Taylor series to bound the error as
f x h f x h
f x max f y
h 2 y( x , x h )
Error between finite difference and actual derivative
Higher Order derivatives
a b x
The integral of f from a to b is the area
under the graph of the function.
If f is continuous, then the area is well
defined, as the common limit of upper and
lower sums. Theb
integral is denoted
f ( x)dx
a
Integration: Fundamental theorem of
Calculus
If a function g is the antiderivative of f, namely
g x f x
a b x
ba
AREA f b f a
2
graph of f(x)
a b x
Composite Trapezoid
graph of f(x)
a b x
graph of f(x)
a b x
Composite Trapezoid
graph of f(x)
a b x
h
Let h=(b-a)/3. The sum of all the approximations is
h
I f (a) f (a h) h f (a h) f (a 2h) h f (a 2h) f (b)
2 2 2
h
f (a) 2 f (a h) 2 f (a 2h) f (b)
2
Derivation of Simpsons Rule:
Suppose f(x)=x3
b
x
3
dx
4
1 4
b a4
a
1
4
b a b 3 b 2 a ba 2 a 3
1
b a 2 b 3 1 b 3 b 2 a ba 2 1 a 3 2 a 3
4 3 3 3 3
1
b a 2 b 3 1 b a 3 2 a 3
4 3 3 3
1 2 3 8 b a 3 2 3
b a b a
4 3 3 2 3
1 3 b a
3
b a b 4 a3
6 2
1
b a f a 4 f b a f b
6 2
Simpsons Rule: Suppose
f(x)=x2
dx
x 2
3
1 3
b a3
a
1 ba
b a f a 4 f f b
6 2
Simpsons Rule: Suppose
f(x)=x
a x dx
2
1 2
b a 2
1 ba
b a f a 4 f f b
6 2
Simpsons Rule: Suppose
f(x)=1
1 dx b a
a
1
b a f a 4 f b a f b
6 2
Simpsons Rule: Derivation
f ( x)dx f ( x)dx
a a
b b b
f ( x) g ( x) dx f ( x)dx g ( x)dx
a a a
b
is f ( x)dx
a
and in the middle
1 ba
I Simpson b a f a 4 f f b
6 2
graph of f(x)
Simpson on 3 subdivisions of [a b]
h=(b-a)/3
a b x
h
h
I S1 f a 4 f a h
2 f a h
6
h
I S2 f a h 4 f a 3 h 2 f a 2h
6
h
I S3 f a 2h 4 f a 5 h 2 f b
6
Add them up. Total of 7 function evaluations.
Composite Simpsons Rule
graph of f(x)
Simpson on 2 subdivisions of [a b]
h=(b-a)/2
a b x
h
I S1 f a 4 f a h 2 f a h
6
h 5 function
I S2 f a h 4 f a 3h 2 f b evaluations
6
giving the approximation as IS=I1S+I2S
h
f (a) 4 f (a h 2 ) 2 f a h 4 f a 3h 2 f b
6
Numerical Integration:
Ad-Hoc stopping criteria
Pick a method (trapezoid, or Simpsons).
Set a stopping tolerance TOL.
Pick k, an initial number of subdivisions
Iterate as below
Apply composite method using k divisions
Apply composite method using 2k divisions
If answers are within TOL, stop, and return the 2k
division answer
If answers are not within TOL, increase k and repeat.
function I = adr(fh,a,b,tol)
Compute I1 using 1 subdivision
Compute I2 using 2 subdivisions
If the answers are within tol, I = I2;
Else
m = (a+b)/2;
ILeft = adr(fh,a,m,tol/2);
IRight = adr(fh,m,b,tol/2);
I = ILeft + IRight;
end
Error Analysis
trapz
fixed trapezoidal approximation
data is vectors x and y (y represents f(x))
1 division between each data pair
quad
Adaptive Simpsons method
Data is function handle, interval endpoints,
stopping tolerance