You are on page 1of 71

MATLAB and Simulink

Prof. Dr. Ottmar Beucher

University of Applied Sciences Karlsruhe


Germany

National Chung Hsing University, Taichung


Summer School 17th - 30th July 2013
What is MATLAB ?

What is MATLAB ?

A tool for numerical calculation and simulation

a higher programming language

a interpreted programming language

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 1
Elementary MATLAB Operations

Elementary MATLAB operations:

arithmetic operations

logical operations

mathematical functions

graphics functions

I/O-operations (data exchange)

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 2
The MATLAB User Interface (since Release 2012b)

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 3
Defining Numerical Arrays (MATrices)


rowvector = [ 1 5 − 3 ]

rowvector =

1 5 −3

columnvector = [ 2 ; 4 ; 3 ; − 1 ; 1 − 4 ∗ j ]

columnvector =

2.0000
4.0000
3.0000
−1.0000
1.0000 − 4.0000 i 

aMatrix = [ 3 1 + 2 ∗ i 2 ; 4 0 − 5 ]

aMatrix =

3.0000 1.0000 + 2.0000 i 2.0000


4.0000 0 −5.0000

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 4
Defining Numerical Arrays (MATrices)


% appending a row v e c t o r ( note : semicolon ) 
aMatrix = [ aMatrix ; 1 2 3 ] 

% appending a row v e c t o r 
aMatrix = [ aMatrix ; rowvector ] 

% appending a column v e c t o r ( note : comma) 


v = [1;2;3];
aMatrix = [ aMatrix , v ] 

% access t o a component 
element23 = aMatrix ( 2 , 3 ) 

% s e t t i n g t o a component 
aMatrix ( 2 , 3 ) = 2 5 

% c a n c e l l i n g a row v e c t o r 
aMatrix ( 1 , : ) = [ ] 

% c a n c e l l i n g a column v e c t o r 
aMatrix ( : , 2 ) = [ ] 

% BUT
aMatrix ( 2 , 3 ) = [ ]
Subscripted assignment dimension mismatch .

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 5
Defining Numerical Arrays (MATrices) - Interactive Access

The Variables Window:

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 6
MATLABs Memory Stack - The ”Workspace”

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 7
Exercises

1 Within MATLAB define the following matrices and vectors and save them in
corresponding variables:

 
1 0 0
 
M=
 0 j ,
1 
j j+1 −3

 
1
 
3 
 
k = 2.75, ~v = 
 ,

 −7 
−0,5
 
~ =
w 1 −5.5 −1.7 −1.5 3 −10.7 ,

 
~y = 1 1.5 2 2.5 ··· 100.5 .

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 8
Exercises

2 Consider the matrix M of the previous exercise:


Enlarge matrix M to a 6 × 6-matrix V, such that
 
M M
V= .
M M

Cancel from matrix V the 2nd row and the 3rd column.
Save the 4th row of matrix V in a new vector r4.
Change component (4, 2) of matrix V to j + 5.
3 Cancel all variables of the workspace and reconstruct matrix V afterwards using
the automatically saved definition commands for V and the ↑- and ↓-keys.
Additionally try to reconstruct other variables using the Command History
Window.
4 Overwrite the 5th row of matrix V with zeros using the Variables Window.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 9
Arithmetic Operations

Matrix algebra operations: M · N, M + N, λ · M


M = [1 2 3; 4 −1 2]; % d e f i n e s 2 x3−m a t r i x M
N = [1 2 −1 ; 4 −1 1; 2 0 1] % d e f i n e s 3 x3−m a t r i x N

V = M∗N % p r o d u c t M∗N ALLOWED !

V =

15 0 4
4 9 −3

W = N∗M % p r o d u c t N∗M NOT ALLOWED !


??? Error using == > mtimes Inner matrix dimensions must agree .


K = [1 5 3; 2 −1 −2]; % d e f i n e s a n o t h e r 2 x3−m a t r i x K
W = N+M; % sums N+M, M+N ALLOWED !


lambda = 2 ; % d e f i n e s a s c a l a r v a l u e ( 1 x1−m a t r i x ) 
V = lambda∗M; % p r o d u c t lambda∗M, M∗lambda ALLOWED !

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 10
Arithmetic Operations

Field operations: M · N, Mk , M/N


M = [1 2 3; 4 −1 2]; % d e f i n e s 2 x3−m a t r i x M
N = [ 1 2 − 1 ; 4 − 1 1 ; 2 0 1 ] ; % d e f i n e s 3 x3−m a t r i x N

V = M. ∗N % f i e l d p r o d u c t M. ∗N NOT ALLOWED !
Error using . ∗
Matrix dimensions must agree . 

K = [1 5 3; 2 −1 −2]; % d e f i n e s a n o t h e r 2 x3−m a t r i x K
V = M. ∗K % f i e l d p r o d u c t s M. ∗ K , K. ∗M ALLOWED !

V =

1 10 9
8 1 −4

k = 3; % d e f i n e s a s c a l a r v a l u e ( 1 x1−m a t r i x ) 
M. ˆ k ; % f i e l d powers ALLOWED !


W = M. / K % f i e l d d i v i s i o n s ALLOWED !
W=

1.0000 0.4000 1.0000


2.0000 1.0000 −1.0000
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 11
Exercises

5 Solve the following problems:


Calculate using matrix- or/and field-operations the standard scalar product of the vectors
   
~x = 1 2 1 −3 −1 and ~y = 2 0 −3 1 2 .
2 3

Calculate the product of the matrices


   
 −1 3.5 2   1 0 −1 
A= and B =  −1.5 .
   
 0 1 −1.3 
  1.5 −3 
1.1 2 1.9 1 1 1

Starting from
 
 −1 3.5 2 
A=
 
 0 1 −1.3 

1.1 2 1.9

calculate the matrix


 
 −1 0 0 
C=
 
 0 1 0 

0 0 1.9

using appropriate field operations!

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 12
Logical Operations

Operations:

and (&)

or (|)

negation (∼)

exclusive Or (xor)

always Field operators


result: logical values, logical arrays

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 13
Logical Operations (Examples)

 
A= [ 1 − 3 ; 0 0 ] Res=A | B % L o g i c a l OR

A = Res =

1 −3 1 1
0 0 0 1

B= [ 0 5 ; 0 1 ] Res=xor (A, B ) % E x c l u s i v e OR

B = Res =

0 5 1 0
0 1 0 1

Res=A&B % L o g i c a l AND Res=˜B % Negation

Res = Res =

0 1 1 0
0 0 1 0

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 14
Relational Operations

Operations:

greater than (>)

less than (<)

greater or equal (>=)

less or equal (<=)

equal (==)

not equal (∼=)

always Field operators


result: logical values, logical arrays

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 15
Logical Operations (Examples)

 
A= [ 1 − 3 ; 0 0 ] Res=A<=B % l e s s o r equal

A = Res =

1 −3 0 1
0 0 1 1

B= [ 0 5 ; 0 1 ] Res=A==B % equal

B = Res =

0 5 0 0
0 1 1 0

Res=A>B % greater Res=A˜=B % n o t equal

Res = Res =

1 0 1 1
0 0 0 1

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 16
Logical and Numerical Indexing

Two types of indexing:

with integer values with logical values


 
A= [ 1 − 3 ; 0 0 ] vect = [ − 2 , 3 , − 4 , 5 , 1 ]

A = vect =

1 −3 −2 3 −4 5 1
0 0
s e l e c t = vect >2 % check elements > 2
a = A( 2 , 1 ) % access t o element ( 2 , 1 )
select =
a =
0 1 0 1 0
0
whos
z = A( 1 : 2 , 1 ) % access t o elements Name Size Bytes Class
% ( 1 , 1 ) and ( 2 , 1 )
select 1x5 5 logical
z = vect 1x5 40 double 

1 pick = vect ( s e l e c t ) % s e l e c t by l o g i c a l
0 % indexing
pick =

3 5

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 17
Exercises

6 Consider the following matrix:


 
1 2 3 4 10
 
 −22 1 11 −12 4 
 
C= .

 8 1 6 −11 5 

18 1 11 6 4
Using appropriate relational operators set all entries > 10 and < −10 of the
matrix C to 0.
Hint: first try to realize the comparisons with > 10 and < −10 and then use the results
to set the entries to 0 with appropriate field operations.
7 Consider the matrix:
 
7 2 3 10
 
 −2 −3 11 4 
 
D= .
 8 1 6 5 
 
18 1 11 4
Using logical fields select the diagonal of D and save it to a vector called diag.
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 18
Mathematical Functions

Act as field operators:


call equivalent to loops like:

t =(0:1:4) % c a l l with a vector double s [ 6 ] ;
f o r ( i = 0 ; i < 6; i ++)
t = {
s [ i ] = sin ( i ) ;
0 1 2 3 4 }

s=sin ( t ) % values of sin ( t )

s =

0 0.8415 0.9093 0.1411 −0.7568

mess = [ 2 5 . 5 1 6 . 3 1 8 . 0 ; . . . % c a l l w i t h a m a t r i x
2.0 6.9 3 . 0 ; . . .
0.05 4.9 1 . 1 ] ; 

double dBmess [ 3 , 3 ] ;
dBmess=20∗ log10 ( mess ) f o r ( i = 0 ; i < 4; i ++)
{ f o r ( k = 0 ; k < 4; i ++)
dBmess = {
dBmess [ i , k ] = 2 0 ∗ log10 ( mess [ i , k ] ) ;
2 8 . 1 30 8 24.2438 25.1055 }
6.0206 16.7770 9.5424 }
− 26.0206 13.8039 0.8279

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 19
Exercises

8 For a time vector between 0 and 10 with equidistant spacing of 0.1 calculate the
values of the signal (function):

s(t) = sin(2π5t) cos(2π3t) + e−0.1t .

9 For a time vector between 0 and 10 with equidistant spacing of 0.1 calculate the
values of the signal (function):

s(t) = 20 sin(2π5t).

Then round the values first towards ∞ and then towards 0. Find the appropriate
functions using MATLAB’s help mechanisms.
In both cases print the first 6 values of s(t) together with their rounded values in
a two row matrix and then interprete the somehow strange result.
10 Using the appropriate elementary mathematical MATLAB function, calculate
the corresponding vector of binary and decadic logarithms for
 
~b =
1024 1000 100 2 1 .

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 20
Plotting Signals and Functions with MATLAB

MATLAB’s plot facilities:

using plot functions in interactive mode and in MATLAB


programs

x − y-plots with plot, stem, stairs, ...


line style options
annotation functions
three-dimensional plots with surf, mesh, ...
plotting multiple functions with subplot

using the Plot Tools Window in interactive mode

customizing plots interactively


documentation of plots

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 21
MATLAB’s x − y-Plot Commands

Using standard plot


Customizing line styles and
commands
annotation

t =(0:1:5); 
s=sin ( t ) ;  t =(0:1:5);
plot ( t , s ) ; % The s i m p l e s t form  s=sin ( t ) ; 
p l o t ( t , s , ’mo ’ ) ; % line style circles
% plotting multiple signals % c o l o r magenta 
t =(0:0.01:2);
s i n f k t =sin (2 ∗ p i ∗5∗ t ) ;  x l a b e l ( ’ time / s ’ ) % a n n o t a t i n g x−
cosfkt=2∗cos(2 ∗ p i ∗3∗ t ) ;  y l a b e l ( ’ ampl . / V ’ ) % and y−a x i s
expfkt =exp(−2∗ t ) ; 
p l o t ( t , [ s i n f k t ; cosfkt ; expfkt ] ) ;  % figure t i t l e 
t i t l e ( ’A sine function ’ ) 

% much b e t t e r  grid % show g r i d 


p l o t ( t , s i n f k t , ’ k−’ , t , cosfkt , . . . axis ( [ 0 , 0 . 5 , 0 , 2 ] ) % show o n l y a s e c t i o n 
’ b−−’ , t , expfkt , ’m. ’ ) 
% adding a t e x t 
t e x t ( 0 . 7 5 , 0 , ’\l e f t a r r o w s i g n a l ’ , . . .
% p l o t t i n g i n l a t t i c e fence s t y l e  ’ FontSize ’ , 1 8 ) 
t =(0:0.05:2);
cosfkt=2∗cos(2 ∗ p i ∗ t ) ; 
stem ( t , cosfkt ) % and much more . . .

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 22
The Plot Tools Window

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 23
The colorredsubplot Command

Multiple plots with subplot


Advantage:

% Example : p l o t t i n g a b s o l u t e v a l u e 
% and argument o f a complex f u n c t i o n 
- plot of multiple functions with
x=(0:0.01:1);
f = ( 1 + j ∗x ) . / ( j −2∗x ) ; % t h e complex f u n k t i o n  same argument but different
unity for function values
subplot ( 2 1 1 ) % s e t t i n g upper p l o t
% window 
p l o t ( x , abs ( f ) , ’ b−’ ) % p l o t abs−v a l u e 
grid % plot a grid

% annotation
x l a b e l ( ’ x−values ’ ) 
y l a b e l ( ’ modulus of f ( x ) ’ ) 

subplot ( 2 1 2 ) % s e t t i n g lower p l o t 
p l o t ( x , angle ( f ) , ’ r−’ )% p l o t argument 
grid % plot a grid

% annotation
x l a b e l ( ’ x−values ’ ) 
y l a b e l ( ’ phase angle of f ( x ) ’ )

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 24
Exercises

11 Insert the following MATLAB commands to the command window and try to interprete the somehow strange graphical
result:


t =(0:0.5:10);
s i n f k t =sin (2 ∗ p i ∗5∗ t ) ; 
cosfkt=2∗cos(2 ∗ p i ∗3∗ t ) ; 
expfkt =exp(−2∗ t ) ; 
p l o t ( t , [ s i n f k t ; cosfkt ; expfkt ] )

12 Try to experiment with the MATLAB functions semilogx, semilogy and loglog.
For this purpose define a frequency vector

ω = (0.01, 0.02, 0.03, 0.04, . . . , 5) rad/s

and try to plot modulus and phase angle of the the so called transfer functions

1
H(ω) =

and

1
H(ω) = .
1 + jω

13 Plot the second transfer function above in a superposed way using a logarithmic scale for the frequency and for the
modulus but not for the phase angle (this is called a Bode diagram).

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 25
MATLAB’s I/O-Operations

MATLAB’s I/O facilities:

using I/O functions in interactive mode and in MATLAB


programs

save workspace or variables with save


load or variables with load
the ASCII interface
specialized functions for many formats

using the Import Data Tool in interactive mode

open the Import Data Tool with uiimport


open the Import Data Tool with menu or double click

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 26
Exercises

14 Using your MATLAB editor create a vector and/or a matrix of real numbers an
save it to a text file.
Delete all matrices of the workspace with clear.
Then, using the load command, try to input the contents of the text file into the
workspace and analyze the result.
15 With MATLAB create a column vector of complex numbers. Save this vector in
MATLAB’s binary format using the save command.
The delete the Workspace with clear and then re-input the contents of the saved
file to MATLAB’s workspace using load or the Import Tool!
Compare the result with that of the previous exercise.
16 Search for an appropriate MATLAB function which may be used to insert the
*.wav-file Tada.wav of the companion software to the workspace.
Then display the audio signal graphically. Take care that the time axis is
annotated correctly.
Then multiply the signal by factor 10 and save it in a *.wav-file using a different
file name.
Listen to the audio signals.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 27
Elementary Matrix Operations

Useful commands for


Reorganizing vectors and
initialization in
matrices:
MATLAB programs:


% I n i t i a l i z i n g w i t h zeros 
M = zeros ( 2 , 2 ) ;  % Transpose a m a t r i x 
M = [ 1 2 ; 3 − j ; −1 j + 1 ] ; 
% I n i t i a l i z i n g w i t h ones  N = M’ ; 
K = ones ( 2 , 2 ) ; 
% Transpose a m a t r i x ( f i e l d −o p e r a t i o n ) 
% I n i t i a l i z i n g with a unit matrix M = [ 1 2 ; 3 − j ; −1 j + 1 ] ; 
E5 = eye ( 5 ) ;  N = M. ’ ; 

% I n i t i a l i z i n g w i t h an empty v e c t o r  % Reorganize as column v e c t o r 


N = []; mVec = M ( : ) ; 

% Determine l e n g t h and s i z e o f a r r a y s  % Reorganize as m a t r i x 


x1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] ;  L = repmat (M, 2 , 2 ) ;
k = length ( x1 ) ; 
[ n ,m] = s i z e (M) ; 

% Determine l a s t component 
l a s t = zVec ( end ) ;

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 28
Exercises

17 Using MATLAB’s help mechanisms, find a function that turns

~y = (1, 1.1, 1.2, 1.3, 1.4, · · · , 9.8, 9.9, 10)

into

~z = (10, 9.9, 9.8, 9.7, · · · , 1.2, 1.1, 1).

18 Consider the vector

~z = (1, 1.5, 2, · · · , 98.5, 99, 99.5, 100).

Using logical operations and using repmat, form this vector


~ containing every third component of ~z !
construct a new vector w

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 29
MATLAB Script Files

Example:
Features:
% S c r i p t −F i l e funkbsp
%
% Aufruf : funkbsp
- collect MATLAB commands to
%
% A MATLAB−S c r i p t −F i l e example
form a program unit
%
% A u t o r : P r o f . Dr . Ottmar Beucher - are executable in command
% HS K a r l s r u h e − Technik und W i r t s c h a f t
% Version : 1 . 0 1 window with file name as
% Date : 1 4 . 1 1 . 2 0 1 2
command
t =(0:0.01:2);
s i n f k t =sin (2 ∗ p i ∗5∗ t ) ;
cosfkt=2∗cos(2 ∗ p i ∗3∗ t ) ; - may use MATLAB’s help
expfkt =exp(−2∗ t ) ;
p l o t ( t , [ s i n f k t ; cosfkt ; expfkt ] ) mechanism
x l a b e l ( ’ Time / s ’ )
y l a b e l ( ’ Amplitude ’ )
t i t l e ( ’ Three b e a u t i f u l signals ’ )
- produce workspace variables,
act on workspace variables !

% launch i n command window 


funkbsp

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 30
MATLAB Functions

Example:
Features:
function [ t , s i n f k t , cosfkt , expfkt ] = . . .

%
funkbsp2 ( f1 , f2 , damp) - collect MATLAB commands to
% F u n c t i o n funkbsp2 form a program unit capable of
%
% C a l l : see below being parameterized
%
% F i r s t example o f a MATLAB−F u n c t i o n - are executable in Command
t =(0:0.01:2); Window with file name as
s i n f k t =sin (2 ∗ p i ∗ f 1 ∗ t ) ;
cosfkt=2∗cos(2 ∗ p i ∗ f 2 ∗ t ) ;
command and with parameters
expfkt =exp(−damp∗ t ) ;
p l o t ( t , [ s i n f k t ; cosfkt ; expfkt ] ) - may also use MATLAB’s help
x l a b e l ( ’ Time / s ’ )
y l a b e l ( ’ Amplitude ’ ) mechanism
t i t l e ( ’ Three b e a u t i f u l signals ’ )
- clear input/output-parameter
interface
% launch i n command window  - act on their own variable stack!
[ t , s i n f k t , cosfkt , expfkt ] = . . .
funkbsp2 ( 2 , 3 , 0 . 1 )
% or simply
funkbsp2 ( 2 , 3 , 0 . 1 )

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 31
MATLAB’s Function Calling Mechanism (Call by Value)

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 32
Exercises

19 Change the code of function funkbsp3 in such way, that you may
externally have access to the contents of componentwise squared
variable a.
20 Change the code of function funkbsp2 in such way, that you may
additionally pass colors and line styles for the graphs of the
signals. The function should then plot the signals in that way.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 33
MATLAB as a Programming Language

MATLAB as a Procedural Programming


Language: Features:

Programming language constructs .


- procedural programming
Control flow . approach
if − C o n d i t i o n a l l y execute
else statements . - commands and constructs
elseif
end similar to other
for − Repeat statements a
programming languages
s p e c i f i c number of times . (like C/C++)
while − Repeat statements an - special commands for
i n d e f i n i t e number of times .
... MATLAB functions with
switch − Switch among several variable parameter lists
cases based on expressions .
...

MATLAB as an OOP Language:


classdef exampleclass
- not treated here.
properties % define class p r o p e r t i e s
end

methods % d e f i n e c l a s s methods
end
end

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 34
Exercises

21 Write a MATLAB function that determines for a given vector of numbers the
maximum of its entries using an appropriate loop construct.
The vector should be the only input parameter, the found maximum the only
output parameter.

22 Write a MATLAB function that determines for a given vector of numbers the
positive entries using an appropriate loop construct.
The given vector should be the only input parameter of the MATLAB function.
The result (the positive entries) should be organized in a vector and this vector
should be the output parameter of the MATLAB function.

23 Write a MATLAB function that plots the signal sin(x) between 0 and 2π in a
given color.
The color should be the input parameter of the MATLAB function having the
following strings as allowed values: ’red’, ’blue’, ’green’, ’magenta’. Use a
switch...case construct to determine internally, according to the input parameter
value, which color to use in the plot command.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 35
Function Handles

Function handles
Features:
- a special kind of pointer:
- a ”pointer” to a

my cos = @cos ;  MATLAB function
whos
Name Size Bytes Class
- main usage:
my cos 1x1 16 function handle  pass MATLAB
value = cos ( 1 )
functions to other
MATLAB functions via
value =
parameter list!
0.5403 

value = my cos ( 1 )

value =

0.5403

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 36
Exercises

24 Revisit the previous exercise (23) and enlarge the functionality of


the program in a way that enables the user to pass a signal and the
plot interval to the MATLAB function. Suppose that the signal is
programmed in a separate MATLAB function or that it is a
built-in MATLAB function.

25 The MATLAB function fzero calculates (using an appropriate


numerical procedure) the root of a real valued function. This real
function, realized as a MATLAB function, has to be passed to
fzero as a function handle.
Familiarize with the calling convention of fzero and calculate the
zeros of example functions calling fzero in the Command Window.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 37
MATLAB’s ODE Solvers

Calling MATLAB’s ODE solvers:


Features:
 - solve initial value problems
help ode23
of type y0 = f (t, y)
ode23 Solve non−s t i f f d i f f e r e n t i a l equations ,
low order method . - solve ODEs of first order or
[ TOUT,YOUT ] = ode23 (ODEFUN, TSPAN, Y0 ) with
systems of first order ODEs
TSPAN = [ T0 TFINAL ] i n t e g r a t e s the system of
d i f f e r e n t i a l equations y ’ = f ( t , y ) from time
- need a user-defined ODE
T0 to TFINAL with i n i t i a l conditions Y0 . function
ODEFUN i s a function handle . - need a time range and a
For a s c a l a r T and a vector Y , ODEFUN( T , Y) vector of initial values
must r e t u r n a column vector corresponding
to f ( t , y ) . - deliver numerical solution
Each row i n the s o l u t i o n array YOUT corres−
ponds to a time returned i n the column at internally defined
vector TOUT. supporting points
To obtain solutions a t s p e c i f i c times
T0 , T1 , . . . , TFINAL , use TSPAN = - are optimized by using step
[ T0 T1 . . . TFINAL ] .
... size steering
See also ode45 , ode113 , ode15s , ode23s , - Runge-Kutta-based
ode23t , ode23tb , ode15i , odeset , odeplot ,
odephas3 , odeprint , . . . . algorithms for non-stiff and
stiff ODEs
Reference page i n Help browser
doc ode23
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 38
The Mathematical Pendulum

Example:
Mathematical model:
initial value problem of second order:

g
α̈(t) = − · sin(α(t)), α(0), α̇(0).
l

or equivalently:

α̇1 (t) = α2 (t),


g
α̇2 (t) = − · sin(α1 (t))
l   
α(0) α
= 1 (0)
α
~ (0) =  .
α̇(0) α2 (0)

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 39
The ODE-file Structure

Structure of an ODE-File
Features:
(example):
- represents the system of 1st
function [ alphadot ] = pendgl ( t , alpha )
% order ODEs
% F u n c t i o n pendgl
% - has a fixed parameter
% C a l l : o n l y c a l l e d by ODE−s o l v e r s
% interface
% Example o f an ODE−f i l e f o r use w i t h
% ode23 , ode45 a . s . o . - does’nt make sense as a
%
function of it’s own! Is
l =10; % l e n g t h o f pendulum
g=9.81; % gravit . acceleration called only by MATLAB’s
%% I n i t i a l i z a t i o n
solvers
alphadot = [ 0 ; 0 ] ; - has to be passed to
%% R e p r e s e n t a t i o n o f t h e f i r s t o r d e r ODEs
MATLAB’s solvers by a
function handle
% f i r s t equation
alphadot ( 1 ) = alpha ( 2 ) ;

% second e q u a t i o n
alphadot ( 2 ) = − ( g / l ) ∗ sin ( alpha ( 1 ) ) ;

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 40
How Solvers Use ODE-file’s Information

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 41
Resistor-Capacitor Lowpass

Example: Mathematical model:

initial value problem of first order:

d 1 1
u(t) = − u(t) + u1 (t), u(0) = u0 .
dt RC RC
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 42
Exercises

28 Solve the initial value problem for the resistor-capacitor lowpass


using different functions as input signals of the lowpass (instead
of u1 (t) take for instance a sinusoidal input).

29 Solve the problem:

ẏ1 (t) = −2y1 (t) − y2 (t) y1 (0) = 1,


ẏ2 (t) = 4y1 (t) − y2 (t) y2 (0) = 1.

Compare the numerical solution with an analytical one (which


you may calculate ”by hand”).

30 Solve the problem:


...
y + 3ÿ + 3ẏ + y = u1 (t), y(0) = 0, ẏ(0) = 1, ÿ(0) = 1.

The function u1 (t) denotes the unit step function.


Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 43
The Symbolic Math Toolbox

Delivers Computer Algebra facilities


two different interfaces

the MuPAD-Notebook: user interface with it’s own command syntax


the MATLAB-adaption: user interface with MATLAB’s command syntax

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 44
Symbolic Calculus Example


syms x y v
whos
Name Size Bytes Class Attributes
v 1x1 60 sym
x 1x1 60 sym
y 1x1 60 sym

f = sin ( x∗y ˆ2) ∗ cos ( v∗x∗y ) % define a function

f =

sin ( x∗y ˆ2) ∗ cos ( v∗x∗y ) 

dfy = d i f f ( f , ’ y ’ ) % d e r i v a t i v e with respect to y

dfy =

2∗x∗y∗cos ( x∗y ˆ2) ∗ cos ( v∗x∗y)−v∗x∗ sin ( x∗y ˆ2) ∗ sin ( v∗x∗y ) 

dfv = d i f f ( f , ’ v ’ ) % d e r i v a t i v e with respect to v

dfv =

−x∗y∗ sin ( x∗y ˆ2) ∗ sin ( v∗x∗y ) 

pretty ( f ) % display expression ” p r e t t y ”

2
sin ( x y ) cos ( v x y )

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 45
Export Symbolic to Numeric

syms x % define symbolic v a r i a b l e s


f = xˆ2 ∗ cos ( x ) ; % define function
df = d i f f ( f , ’ x ’ ) % c a l c u l a t e symbolic d e r i v a t i v e

dt = 0 . 1 ; % d e f i n e sampling s t e p s i z e
t = ( 0 : dt : 1 0 ) ; % d e f i n e sampling p o i n t s
fnum = t . ˆ 2 . ∗ cos ( t ) ; % calculate function numerically

dfnum = d i f f ( fnum ) / dt ; % d i f f e r e n t i a t e function numerically

% p l o t numerical d e r i v a t i v e
p l o t ( ( dt : dt : 1 0 ) , dfnum , ’ b−−’ )

hold
dfnum2 = subs ( df , x , t ) ; % convert symbolic s o l u t i o n to
% a numerical s o l u t i o n with the
p l o t ( t , dfnum2 , ’ r ’ ) % subs−command and p l o t i t

grid
xlabel ( ’x ’ )
ylabel ( ’ derivative ’ )

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 46
Exercises

31 Integrate the function

g(x) = sin(5x − 2)

two times symbolically.

32 Calculate the 3rd-order Taylor-polynomial in x0 = 1 of the


function g(x).

33 Using the symbolic math function dsolve calculate the solution of


the following ordinary differential equation:

ẏ = xy2 .

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 47
Dynamical Systems - a Known Example

Example: Modelling the dynamics:

Zt
1
y(t) = i(τ ) dτ,
C
0
 
1
y(t) = x(t) − i(t) · R ⇐⇒ i(t) = (x(t) − y(t) .
R

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 48
The Simulink Idea

The idea behind Simulink:


draw a block diagram of your dynamical system
let Simulink convert it to a system of differential equations
let Simulink solve this system of differential equations by using
one of MATLAB’s numerical ODE solvers
let Simulink display and save the signals (input signals, output
signals (normally ODE solutions) and internal states
Simulink may be used to:
directly model a given real dynamical system by its block diagram
and simulate the dynamical behavior of that system
solve a system of ODEs by converting the ODEs into a block
diagram and simulating the resulting dynamical system

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 49
Constructing a Simulink Model - The Library Browser

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 50
Constructing a Simulink Model - The Model Window

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 51
Simulating a Simulink Model - The Parameter Panel

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 52
Exercises

34 Check the test system sl test1.slx for different step sizes using a
solver with internal step size control (variable step solvers).
Compare different calculation times when using a step size of
0.00001 directly with the fixed step solver ode3 on one hand and
when using the variable step solvers ode23 on the other hand.

35 Design a Simulink test system sl LsgDiff.slx for the derivative


block Derivative.
The quickest way to do so is to alter the system sl test1.slx.
Then experiment like in the previous exercise.

36 Explain why the result of the test system sl test1.slx represents


the solution of the initial value problem
ẏ(t) = x(t), y(0) = 0.
Which one of the signals is x(t), which one is y(t)?
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 53
Dynamical Systems - Three Examples

Three Examples:

an undamped harmonic oscillation

ÿ(t) = −y(t), y(0) = 1, ẏ(0) = 0.

the resistor-capacitor lowpass

1
T · ẏ(t) + ·y(t) = x(t), T :=
RC

rapid mechanical oscillations in air and fluids

mẍ(t) + b · sgn(ẋ(t)) · ẋ2 (t) + cx(t) = 0.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 54
Exercises

37 Design a Simulink system to solve the nonlinear differential equation


g
α̈(t) = − · sin(α(t)), α(0) = a0 , α̇(0) = a1
l
of the mathematical pendulum (i.e. to simulate the dynamical behavior
of the mathematical pendulum).

38 Creating an appropriate Simulink system solve the following initial


value problem of third order:
...
y (t) + 3ÿ(t) + 4ẏ(t) + 2y(t) = 0, y(0) = 1, ẏ(0) = 1, ÿ(0) = 0.

39 With an appropriate Simulink system solve the ODE-system


ẏ1 (t) = −3y1 (t) − 2y2 (t), y1 (0) = 1,
ẏ2 (t) = 4y1 (t) + 2y2 (t), y2 (0) = 1.

Compare the numerical Simulink solution with an exact one which you
may calculate by hand or using the Symbolic Math Toolbox.
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 55
Simulink System Simplification Methods

Methods: The function block (Fcn)

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 56
Simulink System Simplification Methods

Methods: Creating Subsystems

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 57
Exercises

40 Simplify the Simulink system for the solution of exercise (39) by


defining appropriate subsystem blocks.

41 Create a Simulink system for the solution of exercise (39) using


appropriate Fcn blocks.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 58
Interaction with MATLAB - an Overview

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 59
Interaction with MATLAB - the Config Parameters Panel

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 60
Exercises

42 Design a Simulink system to solve the linear differential equation

mÿ(t) + 2ẏ(t) + 4y(t) = F(t), y(0) = 1, ẏ(0) = 0.

This equation models the movement of an oscillating object with mass m


disturbed by an external force F(t).
In the first experiment use a step function to model the force F(t). The
change from 0 (no disturbing force) to c (constant disturbing force)
should occur at time t0 > 0.
Use workspace variables to parameterize the system.
43 Solve the problem of the previous exercise (42) once again by creating a
new Simulink system that inputs the disturbing external force F(t) with
a From Workspace block and that outputs the result with a To
Workspace block.
44 Solve the problem of the previous exercise (42) once more by creating a
new Simulink system that inputs the disturbing external force F(t) via
an Inport and that outputs the result with an Outport.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 61
Interaction with MATLAB - Data Exchange with Functions

Set parameters of a Simulink system with set param:



% Example : s e t parameter StopTime o f system s l P e n d e l t o 3 0 
set param ( ’ sl Pendel ’ , ’ StopTime ’ , ’ 30 ’ ) 

% Example : s e t parameter Gain o f Block Gain i n system s l P e n d e l t o −1


set param ( ’ sl Pendel / Gain ’ , ’ Gain ’ , ’−1 ’ ) ; 

% Example : s e t parameter Gain o f Block Gain i n system s l P e n d e l t o −g / l 


g = 9.81; % gravity acceleration
l = 25; % l e n g t h o f pendulum 

set param ( ’ sl Pendel / Gain ’ , ’ Gain ’ , num2str(−g / l ) ) ;

Get parameters of a Simulink system with get param:



% Example : g e t parameter StopTime o f system s l P e n d e l 
get param ( ’ sl Pendel ’ , ’ StopTime ’ ) 

% Example : g e t parameter Gain o f Block Gain i n system s l P e n d e l 


set param ( ’ sl Pendel / Gain ’ , ’ Gain ’ ) ; 

% Example : g e t i n i t i a l c o n d i t i o n parameter o f t h e i n t e g r a t o r 
% b l o c k i n system s l P e n d e l 

set param ( ’ sl Pendel / I n t e g r a t o r 1 ’ , ’ I n i t i a l C o n d i t i o n ’ ) ;

Note: This works also from within MATLAB functions!


Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 62
Exercises

45 Revisit the Simulink system of the previous exercise (42) and alter
the parameters via set param before starting it.

46 Launch the Simulink system sl Pendel2.slx of the companion


software. This system simulates the mathematical pendulum.
Alter the parameter pendulum length via set param to 5 m and
then to 8 m before starting the simulation.

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 63
Interaction with MATLAB - the sim Command

The sim command

simulates (an opened) Simulink system

may parameterize the Simulink system via its parameter list

returns simulation data via a return parameter (the


Simulink.SimulationOutput object)

logged signals (see Data Import/Export panel) may be included in


the SimulationOutput object

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 64
The sim Command - the Config Parameters Panel

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 65
The sim Command - Automize Simulink Simulations

Automize Simulink simulations with sim - an example:


function [ z e i t , simuerg ] = simPendel2 ( pendellaenge )

% Open S i m u l i n k system i f i t ’ s n o t open

open ( ’ sl Pendel2 . s l x ’ ) ;

% Set Gain b l o c k parameters


g = 9.81; % gravity acceleration
% update w i t h set param
set param ( ’ sl Pendel2 / Gain ’ , ’ Gain ’ , num2str(−g / pendellaenge ) ) ;

% S i m u l a t e S i m u l i n k system w i t h sim
% make sure t h a t sim r e t u r n s a S i m u l i n k . S i m u l a t i o n O u t p u t o b j e c t
% by s e t t i n g t h e parameter ’ SaveOutput ’ t o ’ on ’
% ( i f sim i s lauched o n l y w i t h t h e S i m u l i n k system name
% o n l y t h e t i m e v e c t o r w i l l be r e t u r n e d )

simOut = sim ( ’ sl Pendel2 ’ , ’ SaveOutput ’ , ’on ’ ) ;

% Access t h e r e s u l t s w i t h t h e g e t method
% and save them i n t o t h e o u t p u t v a r i a b l e s
% o f f u n c t i o n simPendel2

z e i t = simOut . get ( ’ t ’ ) ;
simuerg = simOut . get ( ’ yout ’ ) ;

Note: the system sl Pendel2 may be launched several times this way,
using a for loop and saving the results in matrices or cell arrays!!
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 66
Exercises

47 Write a MATLAB function with which you may simulate the


Simulink system sl Pendel2.slx for a given vector of pendulum
lengths.

48 Design a Simulink system that creates sinusoidal signals using the


sine generator block Sine Wave.
Then write a MATLAB function that is able to launch this
Simulink system several times varying the frequency of the sine
wave.

49 Design a Simulink system that solves the initial value problem


ÿ(t) + ẏ(t) + y(t) = f (t), y(0) = 0, ẏ(0) = 0.
The function f (t) should be a step function (use block Step) with a
step from 0 to h.
Then write a MATLAB function that is able to launch this
Simulink system several times varying the parameter h.
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 67
Look Up Tables

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 68
Look Up Tables - An Example

Tension-current characteristic of a solar cell:

Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 69
Exercises

50 Consider the following characteristic:



 0
 für x < 0,


k(x) = x für x ∈ [0, 4],


2 für x > 4.

Design a Simulink system that realizes this characteristic with a 1-D Lookup
Table. Input a sine wave signal to the Lookup Table and analyze its output
signal. Experiment with different amplitudes of the sine wave.

51 Consider the following two-dimensional characteristic:


k(x, y) = x2 + y2 für x, y ∈ [−1, 1].
Design a Simulink system that realizes this characteristic with a 2-D Lookup
Table.
Then activate the characteristic at points (x, x) with x ∈ [−1, 1]. For this purpose
design an appropriate input signal which you should read from workspace with
a From Workspace block.
Concerning the parameterization of the 2-D Lookup Table compare the steps
needed for creating three dimensional plot (e.g. the function meshgrid)!
Prof. Dr. Ottmar Beucher MATLAB and Simulink - Summer School NCHU, Taichung July 2013 70

You might also like