0% found this document useful (0 votes)
22 views

Introduction to MATLAB (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Introduction to MATLAB (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 77

An Introductory on

MATLAB and Simulink

Muhamad Zahim Sujod


[email protected]
Ext : 2312
Introduction to
MATLAB and Simulink
What can you gain from the course ?
Know what MATLAB/Simulink is
Know how to get started with MATLAB/Simulink
Know basics of MATLAB/Simulink
– know how to solve simple problems
Be able to explore MATLAB/Simulink on
your own !
Introduction to
MATLAB and Simulink
Contents
Introduction
Getting Started
Vectors and Matrices
MATLAB
Built in functions
M–files : script and functions
Simulink
Modeling examples SIMULINK
Introduction
MATLAB – MATrix LABoratory
– Initially developed by a lecturer in 1970’s to help students learn linear algebra.
– It was later marketed and further developed under MathWorks Inc. (founded in
1984) – www.mathworks.com
– Matlab is a software package which can be used to perform analysis and solve
mathematical and engineering problems.
– It has excellent programming features and graphics capability – easy to learn and
flexible.
– Available in many operating systems – Windows, Macintosh, Unix, DOS
– It has several tooboxes to solve specific problems.
Introduction
Simulink
– Used to model, analyze and simulate dynamic
systems using block diagrams.
– Fully integrated with MATLAB , easy and fast to
learn and flexible.
– It has comprehensive block library which can be
used to simulate linear, non–linear or discrete
systems – excellent research tools.
– C codes can be generated from Simulink models for
embedded applications and rapid prototyping of
control systems.
Getting Started
Run MATLAB from Start  Programs  MATLAB
Depending on version used, several windows appear
• For example in Release 13 (Ver 6), there are several windows –
command history, command, workspace, etc
• For Matlab Student – only command window

Command window
• Main window – where commands are entered
Example of MATLAB Release 13 desktop
Variables
– Vectors and Matrices –
ALL variables are matrices

e.g. 1 x 1Variables
4x1 1x4 2x4
3 3 2 i.e1x 7X
4 •They arecase–sensitive  2 1 5 6
2   9 3 2 4
•Their names
  can contain up to 31 
characters 
 9with
•Must start  a letter
 
 3

Variables are stored in workspace


Vectors and Matrices

 How do we assign a value to a variable?

EDU» v1=3 EDU» whos


v1 = Name Size Bytes Class
3 R 1x1 8 double array
EDU» i1=4 i1 1x1 8 double array
i1 = v1 1x1 8 double array
4 Grand total is 3 elements using 24 bytes
EDU» R=v1/i1 EDU» who
R= Your variables are:
0.7500 R i1 v1
EDU» EDU»
Vectors and Matrices

 How do we assign values to vectors?


EDU» A = [1 2 3 4 5]
A =
1 2 3 4 5
A 
A row vector –
 1are 2 3
values 4 5
EDU» separated by
spaces
EDU» B = [10;12;14;16;18]  10
B =  12
10  
A column
12 B –14
vector
14 values are 
16  16by
separated 
18  18
semi–colon
EDU» (;)
Vectors and Matrices

 How do we assign values to vectors?

If we want to construct a vector of, say, 100


elements between 0 and 2 – linspace
EDU» c1 = linspace(0,(2*pi),100);
EDU» whos
Name Size Bytes Class
c1 1x100 800 double array
Grand total is 100 elements using 800 bytes
EDU»
Vectors and Matrices

 How do we assign values to vectors?

If we want to construct an array of, say, 100


elements between 0 and 2 – colon notation
EDU» c2 = (0:0.0201:2)*pi;
EDU» whos
Name Size Bytes Class
c1 1x100 800 double array
c2 1x100 800 double array
Grand total is 200 elements using 1600 bytes
EDU»
Vectors and Matrices

 How do we assign values to matrices ?

EDU» A=[1 2 3;4 5 6;7 8 9]


A =
1 2 3  1 2 3
4 5 6  4 5 6
7 8 9  
EDU»  7 8 9

Columns separated by Rows separated by


space or a comma semi-colon
Vectors and Matrices

 How do we access elements in a matrix or a vector?

Try the followings:


EDU» A(2,3) EDU» A(:,3)
ans = ans =
6 3
6
9

EDU» A(2,:)
EDU» A(1,:)
ans =
ans =
4 5 6
1 2 3
Vectors and Matrices

 Some special variables

EDU» 1/0
Warning: Divide by zero.
beep
ans =
pi () Inf
inf (e.g. 1/0) EDU» pi
ans =
i, j ( 1 )
3.1416
EDU» i
ans =
0+ 1.0000i
Vectors and Matrices

 Arithmatic operations – Matrices

Performing operations to every entry in a matrix


EDU» A=[1 2 3;4 5 6;7 8 Add and subtract
9]
A = EDU» A+3
1 2 3 ans =
4 5 6 4 5 6
7 8 9 7 8 9
EDU» 10 11 12

EDU» A-2
ans =
-1 0 1
2 3 4
5 6 7
Vectors and Matrices

 Arithmatic operations – Matrices

Performing operations to every entry in a matrix


EDU» A=[1 2 3;4 5 6;7 8 Multiply and divide
9]
A = EDU» A*2
1 2 3 ans =
4 5 6 2 4 6
7 8 9 8 10 12
EDU» 14 16 18

EDU» A/3
ans =
0.3333 0.6667 1.0000
1.3333 1.6667 2.0000
2.3333 2.6667 3.0000
Vectors and Matrices

 Arithmatic operations – Matrices

Performing operations to every entry in a matrix


EDU» A=[1 2 3;4 5 6;7 8 9]
Power
A= To square every element in A, use
1 2 3 the element–wise operator .^
4 5 6
7 8 9 EDU» A.^2
EDU» ans =
1 4 9
16 25 36
49 64 81
EDU» A^2
ans =
A^2 = A * A 30 36 42
66 81 96
102 126 150
Vectors and Matrices

 Arithmatic operations – Matrices

Performing operations between matrices


EDU» A=[1 2 3;4 5 6;7 8 9] EDU» B=[1 1 1;2 2 2;3 3 3]
A = B =
1 2 3 1 1 1
4 5 6 2 2 2
7 8 9 3 3 3

 1 2 3  1 1 1   14 14 14 
 4 5 6  2 2 2  32 32 32
    =  
A*B  7 8 9  3 3 3  50 50 50

 1x1 2 x1 3x1  1 2 3
 4 x 2 5x 2 6 x 2  8 10 12 
A.*B   =  
 7 x 3 8x 3 9 x 3  21 24 27 
Vectors and Matrices

 Arithmatic operations – Matrices

Performing operations between matrices

A/B ?

 1/ 1 2 / 1 3 / 1  1.0000 2.0000 3.0000


A./B  4 / 2 5 / 2 6 / 2 =
 2.0000 2.5000 3.0000
   
 7 / 3 8 / 3 9 / 3  2.3333 2.6667 3.0000
Vectors and Matrices

 Arithmatic operations – Matrices

Performing operations between matrices

??? Error using ==> ^


A^B Matrix dimensions
must agree.

 11 21 31   1 2 3 
A.^B  2
4 52
62
=
 16 25 36 
   
 73 83 93   343 512 729
 
Vectors and Matrices

 Arithmatic operations – Matrices

Example:
-j5

j10
2-90o 10 1.50o

Solve for V1 and V2


Vectors and Matrices

 Arithmatic operations – Matrices


Example (cont)

(0.1 + j0.2)V1 – j0.2V2 = -j2

- j0.2V1 + j0.1V2 = 1.5

 0.1  j0.2  j0.2  V1    j2


  j0.2    = 
 j0.1   V2   1. 5 

A x = y
Vectors and Matrices

 Arithmatic operations – Matrices


Example (cont)
EDU» A=[(0.1+0.2j) -0.2j;-0.2j 0.1j]
A =
0.1000+ 0.2000i 0- 0.2000i
0- 0.2000i 0+ 0.1000i
EDU» y=[-2j;1.5]
y =
0- 2.0000i
1.5000
EDU» x=A\y
x =
14.0000+ 8.0000i
28.0000+ 1.0000i
EDU» x=y'/A'
x =
14.0000- 8.0000i 28.0000- 1.0000i
EDU»
Vectors and Matrices

 Arithmatic operations – Matrices


Example (cont)
EDU» V1= abs(x(1,:))
V1 =
16.1245

EDU» V1ang= angle(x(1,:))


V1ang =
0.5191

V1 = 16.1229.7o V
Built in functions
(commands)
Scalar functions – used for scalars and operate
element-wise when applied to a matrix or vector

e.g. sin cos tan atan asin log


abs angle sqrt round floor

At any time you can use the command


help to get help
e.g. EDU>>help sin
Built in functions (commands)
EDU» a=linspace(0,(2*pi),10)
a =
Columns 1 through 7
0 0.6981 1.3963 2.0944 2.7925 3.4907
4.1888
Columns 8 through 10
4.8869 5.5851 6.2832

EDU» b=sin(a)
b =
Columns 1 through 7
0 0.6428 0.9848 0.8660 0.3420 -0.3420
-0.8660
Columns 8 through 10
-0.9848 -0.6428 0.0000
EDU»
Built in functions (commands)

Vector functions – operate on vectors returning


scalar value
e.g. max min mean prod sum length
EDU» max(b)
EDU» a=linspace(0,(2*pi),10); ans =
EDU» b=sin(a); 0.9848
EDU» max(a)
ans =
6.2832
EDU» length(a)
ans =
10
EDU»
Built in functions (commands)

Matrix functions – perform operations on


matrices

EDU» help elmat

EDU» help matfun

e.g. eye size inv det eig

At any time you can use the command


help to get help
Built in functions (commands)

Matrix functions – perform operations on


matrices
EDU» x=rand(4,4) EDU» x*xinv

x=
0.9501 0.8913 0.8214 0.9218 ans =

0.2311 0.7621 0.4447 0.7382


0.6068 0.4565 0.6154 0.1763 1.0000 0.0000 0.0000 0.0000

0.4860 0.0185 0.7919 0.4057 0 1.0000 0 0.0000

EDU» xinv=inv(x) 0.0000 0 1.0000 0.0000

xinv = 0 0 0.0000 1.0000

2.2631 -2.3495 -0.4696 -0.6631


-0.7620 1.2122 1.7041 -1.2146 EDU»

-2.0408 1.4228 1.5538 1.3730


1.3075 -0.0183 -2.5483 0.6344
Built in functions (commands)

From our previous example,


 0.1  j0.2  j0.2  V1    j2
  j0.2    = 
 j0. 1 V
  2  1. 5 

A x = y

EDU» x=inv(A)*y
x =
14.0000+ 8.0000i
28.0000+ 1.0000i
Built in functions (commands)

Data visualisation – plotting graphs

EDU» help graph2d


EDU» help graph3d

e.g. plot polar loglog mesh


semilog plotyy surf
Built in functions (commands) eg1_plt.m

Data visualisation – plotting graphs


Example on plot – 2 dimensional plot

Example on plot – 2 dimensional plot


EDU» x=linspace(0,(2*pi),100);
EDU» y1=sin(x);
Add title, labels and legend
EDU» y2=cos(x);
EDU» plot(x,y1,'r-') title xlabel ylabel legend
EDU» hold
Current plot held Use ‘copy’ and ‘paste’ to add to your
EDU» plot(x,y2,'g--') window–based document, e.g. MSword
EDU»
Built in functions (commands) eg1_plt.m

Data visualisation – plotting graphs


Example on plot – 2 dimensional plot
Example on plot
1
sin(x)
0.8 cos(x)

0.6

0.4

0.2
y1 and y2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
angular frequency (rad/s)
Built in functions (commands) eg2_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot
Supposed we want to visualize a function
Z = 10e(–0.4a) sin (2ft) for f = 2
when a and t are varied from 0.1 to 7 and 0.1 to 2, respectively

EDU» [t,a] = meshgrid(0.1:.01:2, 0.1:0.5:7);


EDU» f=2;
EDU» Z = 10.*exp(-a.*0.4).*sin(2*pi.*t.*f);
EDU» surf(Z);
EDU» figure(2);
EDU» mesh(Z);
Built in functions (commands) eg2_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot
Built in functions (commands) eg3_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot

EDU» [x,y] = meshgrid(-3:.1:3,-3:.1:3);


EDU» z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2);
EDU» surf(z);
Built in functions (commands) eg2_srf.m

Data visualisation – plotting graphs


Example on mesh and surf – 3 dimensional plot
M-files :
Script and function files
When problems become complicated and require re–
evaluation, entering command at MATLAB prompt is
not practical
Solution : use M-files

Script Function
Collections of commands User defined commands
Executed in sequence when called Normally has input &
Saved with extension “.m” output
Saved with extension “.m”
M-files : script and function files (script) eg1_plt.m
At Matlab prompt type in edit to invoke M-file editor

Save this file


as test1.m
M-files : script and function files (script)

To run the M-file, type in the name of the file at the


prompt e.g. EDU>> test1

It will be executed provided that the saved file is in the


known path

Type in matlabpath to check the list of directories


listed in the path
Use path editor to add the path: File  Set path …
M-files : script and function files (script) eg4.m
eg5_exercise1.m
Example – RLC circuit

R = 10 C

+
V L

Exercise 1:
Write an m–file to plot Z, Xc and XLversus
frequency for R =10, C = 100 uF, L = 0.01 H.
M-files : script and function files (script)

Example – RLC circuit

Total impedance is given by:

When XC  XL
1
o 
LC
M-files : script and function files (script) eg4.m
eg5_exercise1.m
Example – RLC circuit
120
Z
Xc
100 Xl

80

60

40

20

0
0 200 400 600 800 1000 1200 1400 1600 1800 2000
M-files : script and function files (script) eg6.m

Example – RLC circuit


R = 10 C
+
V L

For a given values of C and L, plot the following versus the frequency
a) the total impedance ,
b) Xc and XL
c) phase angle of the total impedance
for 100 <  < 2000
M-files : script and function files (script) eg6.m
Example – RLC circuit
Magnitude
100
Mag imp
80
Xc
60 Xl

40

20

0
0 200 400 600 800 1000 1200 1400 1600 1800 2000

Phase
100

50

-50

-100
0 200 400 600 800 1000 1200 1400 1600 1800 2000
M-files : script and function files (function)

 Function is a ‘black box’ that communicates with


workspace through input and output variables.

INPUT FUNCTION OUTPUT


– Commands
– Functions
– Intermediate variables
M-files : script and function files (function)

Every function must begin with a header:

function output=function_name(inputs)

Output variable
Must match the input variable
file name
M-files : script and function files (function)
 Function – a simple example
function y=react_C(c,f)
%react_C calculates the reactance of a capacitor.
%The inputs are: capacitor value and frequency in hz
%The output is 1/(wC) and angular frequency in rad/s
y(1)=2*pi*f;
w=y(1);
y(2)=1/(w*c);

File must be saved to a known path with filename the same as the
function name and with an extension ‘.m’

Call function by its name and arguments

help react_C will display comments after the header


M-files : script and function files (function) impedance.m
 Function – a more realistic example
function x=impedance(r,c,l,w)
%IMPEDANCE calculates Xc,Xl and Z(magnitude) and
%Z(angle) of the RLC connected in series
%IMPEDANCE(R,C,L,W) returns Xc, Xl and Z (mag) and
%Z(angle) at W rad/s
%Used as an example for IEEE student, UTM
%introductory course on MATLAB

if nargin <4
error('not enough input arguments')
end;
x(1) = 1/(w*c);
x(2) = w*l;
Zt = r + (x(2) - x(1))*i;
x(3) = abs(Zt);
x(4)= angle(Zt);
M-files : script and function files (function) eg7_fun.m

We can now add our function to a script M-file

R=input('Enter R: ');
C=input('Enter C: ');
L=input('Enter L: ');
w=input('Enter w: ');
y=impedance(R,C,L,w);
fprintf('\n The magnitude of the impedance at %.1f
rad/s is %.3f ohm\n', w,y(3));
fprintf('\n The angle of the impedance at %.1f rad/s is
%.3f degrees\n\n', w,y(4));
Simulink
Used to model, analyze and simulate dynamic
systems using block diagrams.
Provides a graphical user interface for constructing
block diagram of a system – therefore is easy to use.
However modeling a system is not necessarily easy !
Simulink

Model – simplified representation of a system – e.g. using


mathematical equation

We simulate a model to study the behavior of a system –


need to verify that our model is correct – expect results

Knowing how to use Simulink or MATLAB does not


mean that you know how to model a system
Simulink
Problem: We need to simulate the resonant circuit
and display the current waveform as we change the
frequency dynamically.
i 10  100 uF
Varies  +
from 0 to
v(t) = 5 sin t 0.01 H
2000 rad/s

Observe the current. What do we expect ?

The amplitude of the current waveform will become


maximum at resonant frequency, i.e. at  = 1000 rad/s
Simulink

How to model our resonant circuit ?

i 10  100 uF

+
v(t) = 5 sin t 0.01 H

Taking KVL around the loop,


di 1
v iR  L 
dt C
idt 
Simulink
Differentiate wrt time and re-arrange:
2
1 dv di R d i i
  2
L dt dt L dt LC

Taking Laplace transform:

sV R 2 I
 sI  s I 
L L LC
sV  2 R 1
I  s  s  
L  L LC 
Simulink

Thus the current can be obtained from the voltage:


 
 s(1/ L) 
I V  
2 R 1
s  s 
 L LC 

s(1/ L)
V R 1 I
2
s  s
L LC
Simulink

Start Simulink by typing simulink at Matlab prompt

Simulink library and untitled windows appear

It is where we It is here where we


obtain the blocks to construct our model.
construct our model
Simulink

Constructing the model using Simulink:


‘Drag and drop’ block from the Simulink library
window to the untitled window

1
simout
s+1
Sine Wave Transfer Fcn To Workspace
Simulink

Constructing the model using Simulink:

s(1/ L)
s(100)
2 R 1
s  s 2
s  1000s  110 6
L LC
100s
i
s2+1000s+1e6
Sine Wave To Workspace
Transfer Fcn

To Workspace1
Simulink eg8_sim.mdl

We need to vary the frequency and observe the current

Ramp Amplitude v

w To Workspace3

To Workspace2 100s
1 i
sin s2+1000s+1e6
1000 s To Workspace
Dot Product2 Transfer Fcn1
Constant Dot Product3 Integrator Elementary
Math
Simulink

0.5

-0.5

-1
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

-5
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Simulink eg9_sim.mdl

The waveform can be displayed using scope – similar to


the scope in the lab

5
Constant1

100s
1
2000 0.802 sin s2+1000s+1e6
s Scope
Constant Dot Product2
Slider Integrator Elementary Transfer Fcn
Gain Math
Simulink

Masking

Enable a user to customize a dialog for a block

Change numerical values to variables


Select the block  edit  edit mask  initialize
Simulink eg10_sim_m.mdl

Masking
Simulink

PROBLEM: Suppose we are interested in the response


of the capacitor voltage, vc(t), to a step voltage input
(Vs). What is the waveform of vc as we vary R ?

i 10  100 uF

+ vc –
Vs
0.01 H
Simulink

We need to mathematically model the circuit, i.e. we


need to obtain a transfer function between vc and vs

Taking KVL around the loop:


1 di d 2i
R di i
Vs iR 
C 
i L
dt
 0 2 
dt

L dt LC

Assume the solution i = Aest

st  2R 1  2 R 1
Ae  s  s   0  s  s   0
 L LC   L LC 

Characteristic equation
Simulink

Response will depends on the solution of the


characteristic equation
2 2
R R 1 R 1
   Overdamped
s1       2L  LC
2L  2L  LC 2
R 1
   Critically damped
 2L  LC
2 2
R R 1 R
  
1
s 2       2L  LC
Underdamped
2L  2L  LC

What is the critical value of R ?


Critical value of R = 20 
Simulink

We know that for a capacitor,

Vc 1

I sC

Vs s(1/ L) I 1 Vc
R 1 sC
s2  s 
L LC
Simulink

We may look at the response in two ways:

Method 1
By displaying the response (Vc) using scope as we change R

Method 2
By displaying the response (Vc) using 3–D plot with t and R as the
variables
Simulink

Method 1

•Mask the Vc/V transfer function with R as the variable

•Use Signal Generator as a square wave voltage source, Vs

•Set the stop time to 9999 and simulate the system.

•Observe the response (Vc) using scope –


Note: R can be changed even when the simulation is
running
Simulink

V s(1/ L) I 1
Vc
R 1 sC
s2  s 
L LC
Simulink eg11_sim_square.mdl
Simulink

Method 2

•Simulink file can be run using MATLAB command, sim

•We run the system with different values of R

•Save the results for each simulation

•Plot the results using mesh


Simulink sim_step_3d.m
eg11_sim_step_3D.mdl

for i=1:40,
r=5+i*0.5;
set_param('eg11_sim_step_3D/Subsystem/Transfer Fcn','Denominator','[1 r*100 1e6]');
sim('eg11_sim_step_3D');
for j=1:400,
out(i,j)=vc(j,1);
end;
end;

Note: before we can run sim_step_3d, we need to open


eg11_sim_step_3D
Simulink
Reference
 Internet– search engine
 Mastering MATLAB 6 (Prentice Hall)
– Duane Hanselman
– Bruce Littlefield

You might also like