Li X Zhang Matlab - Notes PDF
Li X Zhang Matlab - Notes PDF
Dr. Li X Zhang
05.12.2007
A Tutorial of Matlab
Dr. L.X.Zhang
Introduction
MATLAB (Matrix Laboratory), a product of Mathworks, is a scientific software
package designed to provide integrated numeric computation and graphics visualization
in high-level programming language. MATLAB offers interactive features allowing the
users great flexibility in the manipulation of data and in the form of matrix arrays for
computation and visualization. MATLAB inputs can be entered at the "command line" or
from "mfiles", which contains a programming-like set of instructions to be executed by
MATLAB. In the aspect of programming, MATLAB works differently from FORTRAN,
C, or Basic, e.g. no dimensioning required for matrix arrays and no object code file
generated. MATLAB offers some standard toolboxes and many optional toolboxes (at
extra cost, of course!) such as signal processing toolbox, statistics toolbox etc. These
toolboxes contain library files called M-Files, which are also functions or command
names, executable from the Command window. Users may also create their own
toolboxes consisted of "mfiles" written for specific applications. The original version of
MATLAB was written in FORTRAN but later was rewritten in C.
1
1. Getting Started: Running Matlab
To start Matlab in Windows environment, double click on Matlab icon from desktop (if
available) or select MATLAB 7.0 menu (from Matlab program group). In the current
settings of most PCs in our labs, the executable file is located at:
Once Matlab's initiation process is completed, a Matlab desktop environment will appear
providing a set of subwindows, a.k.a browsers. In this desktop environment you may
define variables, manage files and objects, execute programs, and view command history.
Workspace window displays the defined variables. The "traditional" Command window
is where the user normally defines variables and enters Matlab pre-defined functions.
You may close, restore, and resize any of these windows. You just type the commands at
the prompt, no variables have to be declared before use, and the values of all variables are
stored for use in the future calculations until overwritten or the session is terminated. You
may list all defined variables in a Matlab session by issuing the command who in
Command Window. One point to be aware of is that all MatLab command lines that end
with a semicolon do not print the result of the assignment, otherwise the result of the
assignment (or the value of the variable if no assignment is being performed) is printed.
For example:
>> A = 1 + 2;
Sets the variable A to be a scalar quantity equal to three, but does not print any output.
> >A
Prints the current value of A, in this case, 3.
2. To Exit
To quit Matlab, simply enter exit (or quit) at Matlab command prompt >> or CTRL+Q
(Windows), or through Matlab’s File menu. If your Matlab process is "frozen" (crashed)
in Windows (XP,2000), you may kill the process from Windows Task Manager
(CTRL+ALT+DEL) by selecting Matlab process and click on End Process button. In
UNIX or LINUX environment, Matlab rarely crashes. In case you need to kill a Matlab
session, find the process ID (PID) number and issue the command kill -9 [process ID].
2
3. Help and demos
• Help
Matlab has an extremely comprehensive help. For those unfamiliar with MatLab the first
resort is to type ‘help’ and you can get most general form of help. Without options lists
all help topics. If an option is entered it then provides help for that particular command.
Always start with this.
Another useful function is ‘lookfor’ which will search through the names of all MatLab
functions and list those which contain the word you have specified.
To get help through the help Window, you can invoke the help menu by typing helpwin
in the command window. Or you can select Help Æ MATLAB Help from the menu bar.
A windowed version of the help list will appear. This help function includes a MatLab
tutorial that you will find extremely useful. The list in the left-hand window is a table of
contents. Notice that the table of contents includes a link to a list of functions, organised
both by category and alphabetically by name. You can use this link to find out what
Matlab functions are available to solve many problems.
• Demonstrations
Large series of examples are available for MatLab by using demo command
>> demo
4. Defining Variables
The best way for you to get started with MATLAB is to learn how to handle matrices. In
MATLAB, a matrix is a rectangular array of numbers. Special meaning is sometimes
attached to 1-by-1 matrices, which are scalars, and to matrices with only one row or
column, which are vectors. For example, an array of data A = 1, 0, 9, 11, 5 is a 1x5
matrix, and a scalar number 9 is an 1x1 matrix. MATLAB has other ways of storing both
numeric and nonnumeric data, but in the beginning, it is usually best to think of
everything as a matrix, even images are usually presented by 2-D matrices. The
operations in MATLAB are designed to be as natural as possible. Where other
programming languages work with numbers one at a time, MATLAB allows you to work
with entire matrices quickly and easily.
3
You can enter matrices into MATLAB in several different ways.
• Enter an explicit list of elements.
• Load matrices from external data files.
• Generate matrices using built-in functions.
• Create matrices with your own functions in M-files.
Start by entering a matrix as a list of its elements. You have only to follow a few basic
conventions:
• Separate the elements of a row with blanks or commas.
• Use a semicolon (;), to indicate the end of each row.
• Surround the entire list of elements with square brackets, [ ].
To store the array A in MATLAB, at the command prompt >> (in Command window),
enter:
To suppress the echo, add a ";" at the end of the input line.
To verify the size of the input array or matrix, use the command "size" as shown below:
,
which verifies the dimension of matrix A as 1x5 (one row and five columns).
In MATLAB, rows are separated by ";" and columns are separated by ",". For example, a
3x5 matrix B with the following elements:
first row: 1, 0, 9, 4, 3
second row: 0, 8, 4, 2, 7
third row: 14, 90, 0, 43, 25
would be entered in MATLAB as follow:
4
Note that you may use a space in place of the comma in separating the column entries.
You may extract a certain group or element from an existing matrix. Say you wish to
create a new array C from the second row of matrix B. Specify the row number and ":"
for all columns in that row as shown below:
Similarly, you may also form a matrix from the element of an existing matrix:
Here, a square matrix D has been created from the specified elements of matrix B.
You may also delete rows and columns from a matrix using a pair of square brackets. For
example, to delete the third column of matrix B, you simply enter
5
5. Complex number
The imaginary unit, −1 , is stored in Matlab in the constants i and j.
>> i^2
ans =
-1.0000+0.0000i
>> z = 3+4*i
z=
3.0000 + 4.0000i
z_bar =
3.0000 – 4.0000i
Using the constant j instead of i yields the same results, although Matlab always uses the
symbol i in the answers it returns, even if we entered the symbol j. We can do the
arithmetic operations to complex numbers in the same way we did with real numbers.
Note, if one of the letters ‘i’ or ‘j’ is used to define some constant or variable, it no longer
means the imaginary unit.
+ Addition
- Subtraction
* Multiplication
/ Division
\ Left division (described in MATLAB help)
^ Power
' Complex conjugate transpose
() Specify evaluation order
6
with simple operation in MATLAB. Please keep in mind of the rules concerning matrix
operations such as the computability issue, e.g., you may not multiply a 2x3 matrix by a
4x2 matrix - the dimensions must agree.
The operations in MATLAB are designed to be as natural as possible. Where other
programming languages work with numbers one at a time, MATLAB allows you to work
with entire matrices quickly and easily.
You will find that Matlab is extremely powerful when performing matrix manipulations
because many scalar operations operate in parallel for all elements of a matrix. This
almost eliminates the need for iterative loops employed in most conventional
programming languages. For example, in order to generate s(n)=sin(2πn/1000) for
n=1,…,1000, we can write the following program in C.
For (n=1;n<=1000;n++){
s(n)=sin(2 * π*n/1000);
}
Since Matlab programs are interpreted (not compiled), for loops and while loops are
inefficient. They should be avoided whenever possible.
7
• Addition “+”
• Subtraction “-”
• Multiplication “*”
8
• Left matrix division. “\”
When you don't specify an output variable, MATLAB uses the variable ans, short for
answer, to store the results of a calculation.
9
How about the row sums? MATLAB has a preference for working with the columns of a
matrix, so the easiest way to get the row sums is to transpose the matrix, compute the
column sums of the transpose, and then transpose the result.
• Transpose
Transposing a matrix in MATLAB involves a simple prime notation ( ' ) after the defined
matrix. It flips a matrix about its main diagonal and it turns a row vector into a column
vector. So
>> sum(A')'
ans =
6
15
15
• Diag
Diag function picks off the diagonal of the array.
>> diag(A)
produces
ans =
1
5
0
• Sort
Sorting columns and rows follow the syntax: B=sort(A,dim), where dim is the dimension
of the matrix with the value 1 for column; 2 for row. Matrix A is the variable specified by
the user.
Example:
Sorting columns:
10
Note that without dim being specified, the default value is 1. The default setting is
ascending order. The variable name of the sorted matrix can be omitted if no needed.
Sorting column in descending order:
• Inverse
The inverse of matrix A can be obtained with the command:
11
where matrix V consists of Eigenvectors. The corresponding Eigenvalues are shown in
matrix E. Eigen values alone can be obtained without the notation "[V,E]":
• Subscripts
The element in row i and column j of A is denoted by A(i,j). For example, A(3,2) is the
number in the third row and second column. For our matrix, A(3,2) is 8. So it is possible
to compute the sum of the elements in the third column of A by typing
>> t = A(4,5)
On the other hand, if you store a value in an element outside of the matrix, the size
increases to accommodate the newcomer:
>> X = A;
>> X(3,4) = 17
12
X=
1 2 3 0
4 5 6 0
7 8 0 17
The colon, :, is one of MATLAB's most important operators. It occurs in several different
forms. The expression
>> 1:10
1 2 3 4 5 6 7 8 9 10
>> 100:-7:50
is
100 93 86 79 72 65 58 51
and
>> 0 : pi/4 : pi
is
>> A(1:k, j)
>> sum(A(1:3,3))
computes the sum of the third column. But there is a better way. The colon by itself refers
to all the elements in a row or column of a matrix and the keyword ‘end’ refers to the last
row or column. So
>> sum(A(:,end))
ans =
9
13
7. Command Input Assistance Feature
Not sure how a command is spelled? Too lazy to type the complete command? Well,
Matlab 7 programmers have added a new feature to answer these questions. Now you
may type only the first few letters of the command and use the TAB key to see what
commands are available or to let Matlab complete the command typing for you. For
example, if you wish to enter the command Cumsum. You may simply type cum then
press the TAB key. A list of commands with spelling close to what you enter will appear
in a pop-up menu.
Select the command using up and down arrows. If the highlighted command is what you
want, then another gentle stroke on the TAB key will complete the command input for
you.
8. Data Format
Matlab handles floating-point numbers in either single precision or double precision
(default setting) format. While double precision numbers use 64 bits, single precision
numbers use 32 bits, based on IEEE Standard 754. You may convert a double precision
number to a single precision number using the command single (number).
You may control the displayed string by using the commands
format type
format ('type')
Available options for type are:
short e (scientific notation, five-digit floating point)
long e (5 digit for single precision and 15 for double precision)
short g (five digits)
long g (7 digits for single precision and 15 for double precision)
format bank (two digit decimal)
format rat (rational)
format hex (hexadecimal)
format loose (line feed added)
format compact (line feed suppressed).
14
Refer to Matlab's help file (help format) for more info. The following examples
demonstrate how Matlab format command displays numbers.
Examples:
>> w=pi/2
w=
1.5708
short g (5-digit number) is Matlab's default format.
>> format long g
>> w
w=
1.5707963267949
15-digit display indicates double-precision setting (default)
To display single-precision result, use the command single(variable) as illustrated below:
>> single(w)
ans =
1.570796
Note that ω is now truncated to a 7-digit number.
To display ω in scientific long format, use
>> format long e
Matlab display:
w=
1.570796326794897e+000
Matlab's answer:
w=
1.5708e+000
To check with Matlab if the results are the same for long g of 2*w and double(2*w), use
15
>> double(pi)==2*w
Matlab's answer:
ans =
which confirms that the two quantities indeed are the same! (1 for yes and 0 for no).
Equivalently, you may ask the question in a different way:
>> double(pi)~=2*w
ans =
Matlab's answer:
w=
1.57
9. Graphical Plotting
Matlab supports graphical plotting on the computer screen and to a printer. The command
for plotting on the screen is plot, which can be used in several formats, as follows.
>> plot(y) % plots vector y versus the index.
>> plot(x,y) % plots vector y versus vector x.
>> plot(x,y,’ <line type>’) % plots vector y versus vector x with the specified
<line type>.
Possible line types include line, point, and color specifications. The command plot can
also take on other forms depending on its argument list. A number of commands are used
to help generate the desired plot. These include: axis, hold, title, xlabel, ylabel, text,
gtext, etc. Please refer to the on-line help for a detailed discussion of these commands.
16
10. Controlling the Environment
A list of “meta” commands useful for controlling the Matlab environment and execution
diary <fname> Save all Matlab output in the file fname until a diary off command is
executed. Useful for recording testing results and saving program
output.
echo. Echo to the screen each line as it is executed until an echo off command is
received. Useful for tracing and debugging but generally confusing for normal
program execution.
Some of the functions, like sqrt and sin, are built-in. They are part of the MATLAB core
so they are very efficient, but the computational details are not readily accessible. Other
functions, like gamma and sinh, are implemented in M-files. You can see the code and
even modify it if you want.
17
pi 3.14159265
i Imaginary unit, -1
j Same as i
eps Floating-point relative precision, 2-52
realmin Smallest floating-point number, 2-1022
realmax Largest floating-point number, (2-ε)21023
Inf Infinity
NaN Not-a-number
The function names are not reserved. It is possible to overwrite any of them with a new
variable, such as
Re-entering the same program, i.e. set of instructions multiple times is wasteful. Ideally
need a means of creating once and re-using as required. Script (M-Files) are Matlab's
mechanism for this.
Create m-file with a text editor (or Matlab's built-in Script editor).
In Matlab command window enter name of script file (e.g., if file called
example1.m then enter example1) to run it.
While still errors in the script
• Modify & save script using editor
• Rerun script in Matlab
Naming
M-files (scripts) must all have the extension ".m"
When a script name is entered Matlab "tacks" an ".m" on the end and looks for a file of
that name. e.g.,
>> example1
18
Matlab searches for a file called example1.m. Matlab employs the following rules in
resolving an identifier entered by the user (e.g., example1):
• Looks for a variable (example1) in the current workspace…if that is not found…
• Looks for a built-in function (example1 ())…if that is not found…
• Looks for a script/m-file (example1.m) in the Matlab's current directory (generally
the one it was started in)…if that is not found…
• Looks for a script/m-file (example1.m) in Matlab's search path (in the order listed
in the search path)
M-File Example:
x = 9.1; % Do something
Running Matlab
>> help helpex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
helpex.m
An example of the way Matlab
uses comments and help to
document a script. If you type
help helpex you will see all of
these comments up till the first
blank line below.
Author: xxxx
Date: 11/2/1999
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> helpex
>> x
19
>> x =
9.1000
We can program our own functions in Matlab. Like script files, function files are also M-
files, but the first word (after possible comments) must be function. Function files take
external arguments, which are enclosed in parentheses immediately after the function
name. For example, to program a function that calculates the hypotenuse of a right-
angled triangle, let us write the following code to a file defined as pyt.m:
function h = pyt(a,b)
% PYT hypotenuse of a right-angled triangle
% by Pythagoras’ theorem.
% Input: the sides (legs of the triangle.)
h = sqrt(a.^2 + b.^2);
Note the use of the array operations a.^2 and b.^2 allows the user to input arrays of side
values. Save the file as pyt.m, and in Matlab command window, type:
>> pyt(3, 4)
ans =
5
Note that function files can accept more than one argument and return more than one
output.
20
Solutions:
1. Create two functions: DR (degrees to radians) and RD (radians to degrees)
2. Describe the Input and Output
3. Equations used
degrees = radians ×180/π
radians = degrees ×π/180
Degrees to Radians
Degrees Radians
0 0
30 0.524
60 1.047
90 1.571
output = x*pi/180;
output = x*180/pi;
Note that these two functions must be in the current directory and must be named
as DR.m and RD.m.
5. Test the function in your command window
>> Clear, clc
21
>> radian1 = DR(degree) (what do you get, refer to the above table!)
6. Develop a MatLab solution and store these commands in a file, test.m, edit it in
the MatLab editor:
% test.m
Clear, clc
% Define a vector of degree values
degrees = 0:15:180;
% call the DR function, and use it to find radians
radians = DR(degrees)
%Create a table to display
Degrees_radians = [degrees; radians]’
Save this file as test.m in the current directory, run it in the command window:
>> test
References
This tutorial is based on the following references:
1. http://edu.levitas.net/Tutorials.
2. Contemporary Communications Systems Using MatLab. J. G. Proakis., M. Salehi, PWS
publishing company.
3. Adrian Biran, Moshe Breiner, Matlab 5 for Engineers, Addison-Wesley, 1999
22
Exercises session I
>> demo
Then go to:
-Toolboxes
Now a selection of choices are open to you. It is advisable for you to investigate all those
you think might be helpful. For example under communications you might find it useful
to explore the bit error rate analysis and the raised cosine filtering, under signal
processing you might find it useful to explore the filter design and analysis and the
spectral analysis and statistical signal processing.
Practice Exercise 2.
Use the help command in the command window to find the appropriate syntax for the
following functions :
a. cos
b. sqrt
c. exp
Practice Exercise 3.
Type the following expressions into MatLab at the command prompt, and observe the
results:
1. 5+2
2. 5*2
3. 5/2
4. 3+2*(4+3)
5. 2.54*8/2.6
6. 6.3-2.1045
7. 3.6^2
8. 1+2^2
9. sqrt(5)
10. cos(pi)
Practice Exercise 4.
23
1. test
2. Test
3. if
4. my-book
5. my_book
6. Thisisoneverylongnamebutisitstillallowed
7. 1stgroup
8. z34wAwy?12#
Practice Exercise 5.
The result is
f = 0.0044
Did you get it?
Practice Exercise 6.
As you perform the following calculations, recall the difference between the * and .*
operators, as well as the / and ./ and the ^ and .^ operators:
Practice Exercise 7.
1. Plot x versus y=sin(x). Let x vary from 0 to 2pi in increments of 0.1 pi.
2. Add a title and labels to your plot
3. plot x versus y1 and y2 for y1=sin(x) and y2=cos(x). Let x vary from 0 to 2pi in
increments of 0.1 pi. Add a title and labels to your plot.
4. Make the sin(x) line in part 3 dashed and red. Make the cos(x) line green and
dotted.
24
5. Add a legend to the graph in part 4
Practice Exercise 8 Compute and plot x(n) = e −0.003 n cos(2πn / 100 + 3) , for
n=1,…,1000. On the same graph, plot e −0.003 n and - e −0.003 n with different colors and line
types. Label the curves to identify each one.
Solution:
>> t=(0:.01:10);A=2;phi=pi/2;omega=5;
>> xt=A*cos(omega*t+phi);
>> plot(t,xt);grid
Figure
Practice Exercise 10. Synthesize a square wave function which is symmetric about t=0
using Fourier series, and observe the effect of the number of terms. The Fourier series of
the square wave is:
25
4A 1 1 1
x (t ) = (cos ωt − cos 3ωt + cos 5ωt − cos 7ωt + ...)
π 3 5 7
where A is the amplitude of the wave and ω its angular frequency. Assume A=1 and
ω = 2π here.
Solution:
On a computer, we can only generate a finite number of terms, therefore, we can only
synthesize the signal approximately. Initially we use only three terms. The required
Matlab commands are:
>> t=-2:0.05:2;
>> omega=2*pi;
>> x1=cos(omega*t);
>> x2=-cos(3*omega*t)/3;
>> x3=cos(5*omega*t)/5;
>> x=4*(x1+x2+x3)/pi;
>> plot(t,x),grid;
>> xlabel('t')
Observe the truncation error due to limited number of terms. To improve the
approximation, try to add more terms. However, it is obvious that the operation would be
tedious with more terms, try to use FOR loop and make it as a function of the number of
terms.
26
Exercises session II
Practice Exercise 1. The propulsion power requirements for a spacecraft are determined
by a simple equation:
F=ma
In other words, force(F) is equal to mass (m) times acceleration (a). Work (W) is force
times distance (d), and since power (P) is work per unit time, power becomes force times
velocity (v):
W = Fd
P=W/t =F×d/t = F×v = m × a ×v
The power production of Voyager 1 and 2 spacecraft is about 335 watts, if this power is
diverted to propulsion, how much acceleration would it produce in the spacecraft?
Voyager 1 is currently traveling at a velocity of 3.50 AU/year, and Voyager 2 is
traveling at 3.15 AU/year. Each spacecraft weights 721.9kg. Can you develop a MatLab
solution using M-script?
Hint: m/sec = AU/year * 150e9/365/24/3600
Result: a = 1.0e-004 * [0.2788 0.3097
27
c. Find ex
d. Find ln(x) and log10(x) and explain your result
e. Use the sign function to determine which of the elements in x are positive.
Practice Exercise 3.
Calculate the following:
1. sin(2x) for x =0:0.2pi: 3pi, plot the results again x
2. sin-1(1)
3. Find the angle whose sine is 0.5. Is your answer in degrees or radians.
Practice Exercise 4 use of function max (use help to see how to use this function)
Consider the following matrix:
⎡4 90 85 75 ⎤
⎢2 55 65 75 ⎥⎥
x=⎢
⎢3 78 82 79 ⎥
⎢ ⎥
⎣1 84 92 93 ⎦
Practice Exercise 5.
Consider the following matrix:
⎡4 90 85 75 ⎤
⎢2 55 65 75 ⎥⎥
x=⎢
⎢3 78 82 79 ⎥
⎢ ⎥
⎣1 84 92 93 ⎦
1. use the size function to determine the number of rows and columns in this matrix
28
2. use the sort function to sort each column in ascending order
3. use the sort function to sort each column in descending order
4. use the sortrows function to sort the matrix so that the first column is in
ascending order, but each row still retains its original data. Your matrix should
look like this:
⎡1 84 92 93 ⎤
⎢2 55 65 75 ⎥⎥
x=⎢
⎢3 78 82 79 ⎥
⎢ ⎥
⎣4 90 85 75 ⎦
Practice Exercise 6.
1. Create a vector D of complex numbers whose real components are 2, 4 and 6 and
whose imaginary components are -3, 8, and -16.
2. Find the magnitude (absolute value) of each of the complex numbers you created
in 1. (function abs)
3. Find the angle from the horizontal of each of the complex numbers you created in
in 1. (function angle)
4. Find the complex conjugate of vector D. (function conj)
5. Use the transpose operator to find the complex conjugate of vector D.
Practice Exercise 6.
1. Use the clock function to add the time and date to your work sheet.
2. Use the date function to add the date to your work sheet.
3. Convert the following calculations to MatLab code and explain your results:
a. 322!( ! means factorial to a mathematician)
b. 5 × 10500
c. 0/0
Practice Exercise 7.
Create MatLab functions to evaluate the following mathematical functions
29
1. y(x) = x2
2. y(x) = sin(x2)
Practice Exercise 8.
Assuming that the matrix dimensions agree, create and test MatLab functions to evaluate
the following simple mathematical functions:
1. z(x,y) = x+y;
2. f(x) = exp(x), f(x) = ln(x)
3. f(x,y) = x+y, f(x,y) = x-y
Solution:
The reactance of the capacitor equals:
1 1
Zc = =−j
jω C ωC
30
>> V = 0.01; %V
>> C = 100*10^(-12); %F
>>Z = R+Zc
Z=
15.0000 – 31.8310i
I=
1.2114e-04 + 2.5707e-04i
Vr =
0.0018 + 0.0039i
Vc =
0.0082 - 0.0039i
Let us plot side by side the phasor diagram and the time plots of the calculated voltages
using the Matlab subplot command:
>> subplot(1,2,1)
The argument 1, 2, 1 means that a 2 side by side graphs will be produced, and the next
plot is the first one on the left. Consider the values of V, Vr, Vc as the ends of the
phasors. To define the phasors we must also enter their origins:
>> VV = [0 V]; VVc = [0 Vc]; VVr = [0 Vr];
31
Note that a square plotting frame is needed for the same scale of the real and imaginary
axis in order to view the phasors correctly. And the extension of the axis must be greater
than the maximum phasor magnitude. The graph is completed with:
>> hold on;
>> title(‘(a)’)
Note that the text commands are used to identify the phasors. To draw the time plots of
the calculated voltages, we begin with:
>> f = 50*10^6; % frequency, Hz
>> v = V * sin(omega*t);
>> grid ;
>> title(‘(b)’) ;
In the plot, the argument ‘k- ‘ means that the first line should be solid and black. The
argument ‘r- -‘ produces a dashed, red line, and ‘g:’, a green, dotted line. By writing
h=plot(… we assign a handle to the plot. We use it in calling the function legend, which
can be checked on the graph. The plot of the voltages in the series RC circuit is shown in
the following figure:
32
Figure: Voltages in the series RC circuit
Note that the solution is given using commands in Matlab commands window. Can you
write them in an M-file, and can you write it as a function of values of V, R and C? Save
the file to directory where you can specify the path from the MATLAB command
window. Once saved, this M-file can be loaded (executed) by simply going to the
appropriate directory and call the M-file by its name. NOTE: Make sure not to save your
M-file with a name that is the same as a Matlab reserved word or function name.
Solution
The matlab file is given as follows:
function Y=rndprm1(X);
%RNDPRM1 random permutation of row vector using For loop,
% X is a row vector
33
Y = []; % start from an empty array;
e = n; % number of elements of X
for i = 1 : n
i = 1 + fix(e*rand); % select at random the position of the next element of Y
x = X(i); % selected element
Y = [Y, x]; % add x to the Y list
X(i) = []; % take out x from the X list
e = e-1; % update number of X elements
end % end for block
Note that this implementation uses a FOR loop. Can you attempt to use a WHILE loop to
implement the same function?
34
A Tutorial of Simulink
Dr. L.X.Zhang
Introduction
Simulink is provided as an add-on to MatLab (at extra cost, of course!) for modelling and
simulating dynamic systems. Simulink provides a graphical user interface, which can be
used to build systems as block diagrams using click-and-drag mouse operations. A
comprehensive set of functional blocks is provided as standard, including a variety of
data sources, sinks, mathematical and data processing functions. It is also possible to
create your own blocks with specific functionality. Simulation models are developed by
connecting together a series of blocks, which represent different functions and
components of a system. It allows the real time display of signals. Simulink is integrated
with Matlab, enabling Simulink models to be run from the Matlab workspace or function
files. Simulink is a time-flow simulator, so intermediate results are available and can be
displayed while the simulator is running.
1. Running Simulink
To create a model click on ‘File Æ New Æ Model’ or alternatively the NEW FILE
ICON. A new window will appear on the screen. You can construct and simulate your
model in this window.
To save a model, you may click on the floppy diskette icon or ‘File Æ Save’. All
Simulink model file will have an extension ".mdl". Simulink recognises file with .mdl
extension as a simulation model (similar to how MATLAB recognises files with the
extension .m as an MFile).
45
To become familiarized with the structure and the environment of Simulink, you are
encouraged to explore the toolboxes and scan their contents. You may not know what
they are all about but perhaps you could catch on the organisation of these toolboxes
according to the category. Click on the "+" sign next to each group to expand the tree and
select one of the categories (for example, Source, or Sink), a set of blocks will appear in
the BLOCKSET group on the right of the ‘Simulink Library browser’. You can find help
by selecting the block and clicking on the right mouse button.
The best way to learn Simulink (or any computer program in general) is to practice and
explore. Therefore, we will use a simple model to introduce how to use Simulink to
simulate your system. Please follow the steps below to construct a simple model.
Example: Suppose you want to model the response of a first order process model given
by the following equation:
dT 1
= (Tin − T )
dt τ
T (0) = T0
where τ is the residence time parameter, Tin is the inlet temperature and T is the
temperature of the continuously stirred tank.
STEP 1: CREATING BLOCKS.
Open up a worksheet for a new Simulink model by clicking on ‘File Æ New Æ Model’.
Click on ‘Math Operations’ under the ‘Simulink’ list and drag a copy of ‘Gain’ block
across to the worksheet by holding down the left mouse button. Drag a copy of ‘Sum’
block across as well. In the same way, drag a copy of ‘Integrator’ block from
‘Continuous’, a copy of ‘Step’ block from ‘Source’, and a ‘Scope’ block from ‘Sinks’.
Now you have established a source of your model. Note that:
1. If you wish to locate a block knowing its name, you may enter the name in the
SEARCH WINDOW (at Find prompt) and Simulink will bring up the specified
block.
2. To move the blocks around, simply click on it and drag it to a desired location
3. You may remove (delete) a block by simply clicking on it once to turn on the
"select mode" (with four corner boxes) and use the DEL key or keys combination
CTRL-X.
Once you've dragged over all necessary blocks, you could move the blocks (via click-
drag) around in the model window to match what is shown in figure 1:
46
Figure 1.
At this point, it may be instructive to layout the roles and connections among these five
blocks:
• The Sum block will be used to take the difference: (Tin-T) Note, we need to
change the properties of this bock to perform subtract instead of sum (which we
will do in the step of Parameter Setting).
• The Gain block will be used to change the difference (Tin-T) by a factor. In our
case, this factor will be 1 τ . Thus the output of the Gain block will be
(1 τ )(Tin − T ) . In reference to the process model, the calculations yield the value
of the derivative dT dt .
• The Integrator block now takes in the dT dt signal and outputs the desired T
signal.
• The Scope block now simply reads in the T signals as a function of time and plots
it in a separate window.
STEP 2: CONNECT UP BLOCKS
Connect up these blocks as shown in the diagram below, by picking up a wire from the
output of any block (the “>” sign) with the left mouse button (once placed at the output,
the cursor will turn into a cross “+” enabling you to make connection between blocks),
holding the mouse button down, and dragging it to the input of another block.
Alternatively, to connect two blocks, first click on one block then CTRL-click on the
other block. An arrow should connect the two blocks. (Note: the sequence of blocks
clicked will determine the direction of the arrow.)
Note that we need to split the T signal that goes to the Scope block and feed it back to the
Sum block. To pick up a new wire from an existing wire, use the right mouse button. To
resize the signal line, click on it once and then drag the black corners.
47
To delete one connection, select it by clicking on it once, and use the DEL key.
The connected model is shown below.
Figure 2
STEP 3: PARAMETER SEETINGS
Before starting the simulator, some of the parameters must be changed to reflect the
requirements of your simulation. Double-click the ‘Step’ block and fill in 3 in the ‘Step
time’ box, 20 for the ‘Initial Value’, and 30 for the ‘Final value’. This means Tin will
have a value of 20 until the t = 3. After that, Tin will jump to a value of 30. As we
mentioned, we need to change the ‘Sum’ block to obtain a difference. To do so, double-
click the ‘Sum’ block, in the “List of Signs” input box, change the original entry to “|+-”.
Then click the [OK] button to close this window. In the same way, set up the ‘Gain’
block to have a gain of 0.25 (suppose we want to use a value of τ = 4 for our time
constant, this means the reciprocal, 1 τ = 0.25 ). Finally, double click on the ‘Integrator’
block, and fill 20 in the “Initial value” box. This means we are setting T0=20.
STEP 4: RUNNING SIMULATION
Set the simulation parameters by selecting SimulationÆConfiguration Parameters. Set
the stop time to 20.0 (alternatively entering 20 in the small window on the icon bar).
Remember to save the model under an appropriate name (for later reference, this model is
saved as simple.mdl). Run the simulation by clicking on the play button , or
Simulation Æ Start.
Double click on the Scope block and bring up the display window. To see the whole plot,
click the “Autoscale” button . The output is shown in the following figure:
48
Figure 3
49
3. Handling of Blocks and Lines
The table below describes the actions and the corresponding keystrokes or mouse
operations (Windows versions) [1].
Actions Keystokes or Mouse Actions
Copying a block from a library Drag the block to the model window with the left button
on the mouse OR use EDITÆ COPY and EDITÆPASTE.
Duplicating blocks in a model Hold down the CTRL key and select the block with the left
mouse drag the block to a new location.
Display block's parameters Double click on the block
Flip a block (Rotate the block 180
Right click on the block and use FormatÆ Flip block.
degree)
Rotate a block (clockwise 90 deg @ CTRL-R, or Right click on the block and use FormatÆ
each keystroke) Rotate block.
Changing blocks' names Click on block's label and position the cursor to desired
place.
Disconnecting a block hold down the SHIFT key and drag the block to a new
location
Change block’s background colour Right click on the block and select the colour from
Background colour menu.
Drawing a diagonal line from an hold down the SHIFT key while dragging the mouse with
existing line the left button
Dividing a line move the cursor to the line to where you want to create the
vertex and use the left button on the mouse to drag the line
while holding down the SHIFT key
4. Add Annotations
Annotations provide textual information about a model. You can add an annotation to any
unoccupied area of your block diagram. To create a model annotation, double click in an
unoccupied area. A small rectangle appears and the pointer changes to a vertical insertion
bar. Start typing the annotation content. To start a new line, simply press the Enter key.
Each line is centered within the rectangular box that surrounds the annotation. To close
the annotation, click with the mouse elsewhere in the window.
To delete an annotation, select the annotation, then press the DELETE or BACKSPACE
key. You can also change font type and colour from FORMAT menu. Make sure that the
block is selected before making the change.
50
5.Running Simulink Models from MatLab Functions
Running Simulink models directly can become rather tedious when we wish to evaluate
the performance of a system with a significant number of different parameter values. In
order to speed up this process, Simulink simulations can be run from within Matlab
functions using the ‘sim’ function as follows:
>> output = sim(‘Model_name’);
This is especially useful when you need to change parameters for a range of say 10
values. You could change parameters using a Matlab script file and then collect the
results in a structure or a file for further processing. To change the parameter value in a
Simulink model while in a Matlab command window, use command “set_param”. For
example, to change the input for the ‘Gain’ parameter to 0.3 in the above example, we
use:
>> set_param(‘simple/Gain’, ‘Gain’,’0.30’);
For the purpose of data processing via Matlab commands, double click on the ‘Scope’
block in your model and click on the second icon from the left to change its parameters.
Select the ‘Save data to workspace’ option, enter the name ‘T’, and change the format to
‘Array’. Next in the Model window, select “Simulation Æ Configuration Parameters”,
and choose “Workspace I/O” tab, click on the “Time” variable and change the name from
tout to time. Also change the Format to Array. Then, after run your simulation (either
in Simulink or via Matlab commands), you should now have two vectors available in the
workspace: time and T, which you can plot or perform other forms of data processing in
Matlab windows. For example:
>>plot(time, T(:,2));
You will obtain the same plot as shown in figure 3.
51
6.Exercises
Exercise 1. Simulation of an Equation [1]
Please use Simulink to model an equation:
x(t ) = A cos(ωt + φ )
Solution:
Step1: From Simulink's library drag the following blocks to the Model Window
Figure 4
Step 3: Double click on the blocks and enter the appropriate values as prompted
by the pop-up dialog windows. Note that the cosine function can be selected from
the pull-down menu (Functions) in the parameter window of the Trigonometric
function. In the arrangement shown above, the input signal (a ramp function) is to
be displayed along with the output (displacement) via the use of the mux tool. To
view the plots, double click on the scope.
Step 4. Run the simulation. You may need to select the Autoscale button on the
scope display window to obtain a better display of the plots.
52
This exercise has demonstrated the use Simulink with built-in mathematical
functions and other supporting toolboxes to simulate an equation. Note the same
output/result has been obtained in Matlab command window in exercise 3 of last
session.
Solution:
Step 1: From Simulink's library drag the following blocks to the Model Window:
Click on ‘Sources’ under the ‘Simulink’ list and drag a copy of ‘Band-limited White
Noise’ across to the worksheet. Drag a copy of ‘Random Number’ across as well. In the
same way, drag a couple of ‘Sum’ blocks, a couple of ‘Sign’ blocks, an ‘Abs’ block, and
a ‘Gain’ block from ‘Math Operations’, and a ‘Scope’ block from ‘Sinks’. Now you have
established a source of your model. Once you've dragged over all necessary blocks, the
workspace window should consist of the following components:
Figure 5
Step 2: Connect up these blocks as shown in the diagram below:
53
Figure 6
Step 3: Before starting the simulator, some of the parameters must be changed to reflect
the requirements of your simulation. Double click on the ‘Band-limited White Noise’
block and fill in ‘1’ in the ‘Sample time’ box (so it will generate a new value once per
second). Input 0.1 in the ‘Noise power’ box for a signal to noise ratio of 10 dB. Then
click ‘OK’ to accept these new values. Double click on the ‘Random Number’ block and
fill in ‘1’ in the ‘Sample time’ box (so it will generate a new value at the same time as the
noise generator, once every second) and click ‘OK’. Also, set up the ‘Gain’ block to have
a gain of 0.5, and remember to edit the second ‘Sum’ block to perform subtraction rather
than addition by changing the list of signs to ‘+-’. Double click on the ‘Scope’ block and
click on the second icon from the left to change its parameters. Move to the ‘Data
history’ tab and change the ‘Limit data points to last’ to 100,000. Select the ‘Save data to
workspace’ option, enter the name ‘simout’, and change the format to ‘Array’. Now the
model is ready to run.
Step 4: Set up the number of cycles you want to run the model by entering 100000 in the
small window on the icon bar, and remember to save the model under an appropriate
name. Run the simulation by clicking on the play button, or from the Simulation menu.
Double click on the Scope block and bring up the display window. Examine the output
vector (simout) to see how the Simulink model records the occurrence of errors as a
function of time, as shown in figure 7.
This exercise generates a series of random data +1 or -1 using the Random Number
followed by the Sign block. Gaussian noise (Band-Limited White Noise block) is added
to this signal and the corrupted signal will pass Sign block and generate data values +1 or
-1. This signal will be compared with the original signal using the second Sum (of
course, we need to change the property of this block to perform subtract rather than sum).
Note that if the two signals are same, the output of Abs block is 0, otherwise, is 1.
Therefore, the number of 1’s displayed using Scope represents the number of errors
occurring at this level of noise at the receiver.
54
Figure 7
Exercise 3: Mass-spring-dashpot system simulation [1]
Consider a mass-spring-dashpot system as shown in figure 8. The mathematical model
for this system is described by
mx + cx + kx = f (t ) (1)
where m is the equivalent mass of the system, c is the damping ratio, k is the spring
stiffness, and f(t) is the forcing function in the x-direction. Please use Simulink to
simulate the response of this system to unit step input.
Figure 8
Solution:
Step 1: From Simulink's library drag the following blocks to the Model Window:
Step from Sources, Gain, Sum from Math Operation, Integrator from Continuous,
and Scope from Sinks.
55
Step 2: Re-arrange (1) to yield an expression for the acceleration term:
1
x=
( f (t ) − cx − kx) (2)
m
Based on equation (2), duplicate three Gain blocks and two Integrator blocks, and place
the blocks as shown in figure 9, flip and rotate the blocks as necessary. Then connect the
blocks as shown.
Figure 9
Step 3: Double click on the blocks and enter the appropriate values as prompted by the
pop-up dialog windows. Here, we set m=2.0; c=0.7; k=1. Note the parameters you need to
fill in the three Gain blocks should be 1/m, c/m, k/m individually. You are encouraged to
try different values and observe the system’s response to step input.
Step 4: Enter 30 in the small window on the icon bar and run the simulation by clicking
on the play button, or from the Simulation menu. The output from the Scope block is
shown in figure 10.
56
This exercise models and simulates a second-order under-damped dynamic system. To
exam different response, feel free to change different values for m, c and k in the Gain
blocks.
Exercise 4:Using the same system presented in exercise 3, simulate the response using
transfer function approach (frequency domain approach) [1].
Based on equation (2) and figure 9, using the same values for m, c, and k as in Exercise 3,
we can deduce the transfer function of the step response of the step input as
1
H= (3)
2 s + 0.7 s + 1
2
Note that the derivation of mathematics model is beyond the scope of this workshop.
Solution:
Step 1: From Simulink's library, drag the following blocks to a new Model Window:
Step from Sources, Gain, Transfer Function from Continuous, and Scope from Sinks.
Step 2: Arrange and connect the blocks as shown in figure 11.
57
For the purpose of data processing via Matlab commands, double click on the ‘Scope’
block and click on the second icon from the left to change its parameters. Select the ‘Save
data to workspace’ option, enter the name ‘x’, and change the format to ‘Array’. Next in
the Model window, select “Simulation Æ Configuration Parameters”, and choose
“Workspace I/O” tab, click on the “Time” variable and change the name from tout to
time. Also change the Format to Array.
Step 4: Run the simulation in Simulink. The step response displayed in the Scope block is
shown in figure 12.
Reference
[1] http://edu.levitas.net/Tutorials.
58