MATLAB & SIMULINK
--- Ami Sheth
Programming in MATLAB
Mathematical modeling and simulation in
MATLAB & SIMULINK
Introduction
MATrix LABoratory
High-performance language for technical computing
It
integrates
computation,
programming environment.
visualization,
and
An excellent tool for teaching and research:
Modern programming language environment. It has
sophisticated data structures, contains built-in editing and
debugging
tools,
and
supports
object-oriented
programming.
It also has easy to use graphics commands
that make the visualization
immediately available.
Specific
of
results
applications are collected in
packages referred to as toolbox. There are
toolboxes for signal processing, symbolic
computation, control theory, simulation,
optimization, and several other fields of
applied science and engineering.
Starting MATLAB sesson
The goal of this minimum session is to learn
the first steps:
How to log on
Invoke MATLAB
Do a few simple calculations
How to quit MATLAB
Using MATLAB as a calculator
For example, let's suppose you want to calculate the
expression, 1 + 2 * 3. You type it at the prompt
command (>>) as follows,
>> 1+2*3
ans =
7
>> x = 1+2*3
x=
7
>> 4*x
ans =
28.0000
Getting Started
Creating MATLAB variables
variable name = a value (or an expression)
For example,
>> x = expression
where expression is a combination of numerical
values, mathematical operators, variables, and
function calls.
expression can involve:
manual entry
built-in functions
user-defined functions
Overwriting variable
Once
a variable has been created, it can
reassigned. If you do not wish to see
intermediate results, you can suppress
numerical output by putting a semicolon (;) at
end of the line.
Then the sequence of commands looks like this:
>> t = 5;
>> t = t+1
t=
6
be
the
the
the
Error messages
If we enter an expression incorrectly, MATLAB
will return an error message.
For example, in the following, we left out the
multiplication sign, *,
>> x = 10;
>> 5x
??? 5x
|
Error: Unexpected MATLAB expression.
Making corrections
To make corrections, we can, of course
retype the expressions. But if the
expression is lengthy, we make more
mistakes by typing a second time. A
previously typed command can be recalled
with the up-arrow key ". When the
command is displayed at the command
prompt, it can be modified if needed and
executed.
Controlling the hierarchy of
operations or precedence
Let's consider the previous arithmetic operation, but
now we will include parentheses. For example, 1 + 2
*3
>> (1+2)*3
ans =
9
>> 1+2*3
ans =
7
Controlling the appearance of
floating point number
MATLAB by default displays only 4 decimals in the result of the
calculations, for example 163.6667.
However, MATLAB does numerical calculations in double precision,
which is 15 digits. The command format controls how the results of
computations are displayed.
>> format short
>> x=-163.6667
If we want to see all 15 digits, we use the command format long
>> format long
>> x= -1.636666666666667e+002
To return to the standard format, enter format short, or simply format.
Managing the workspace
>> clc: To clear the Command Window
>> clear
The command clear or clear all removes all
variables from the workspace
>> whos
whos will give more details which include size,
space allocation, and class of the variables
Entering multiple statements per
line
It is possible to enter multiple statements per line.
Use commas (,) or semicolons (;) to enter more
than one statement at once.
Commas (,) allow multiple statements per line
without suppressing output.
>> a=7; b=cos(a), c=cosh(a)
b=
0.6570
c=
548.3170
Getting help
To view the online documentation, select MATLAB Help
from Help menu or MATLAB Help directly in the
Command Window. The preferred method is to use the
Help Browser.
Help Browser can be started by selecting the ? icon
from the desktop toolbar.
Information about any command is available by typing
>> help Command
Use on-line help to request info on a specific function
>> help sqrt
Mathematical functions
Elementary functions
Predefined numbers
Examples
for a = 5, x = 2, an
For a=5,x=2,y=8
>> a = 5; x = 2; y = 8;
>> y = exp(-a)*sin(x)+10*sqrt(y)
y=
28.2904
>> log(142)
ans =
4.9558
>> log10(142)
ans =
2.1523
Cont
sin(pi/4) and e10,
>> sin(pi/4)
ans =
0.7071
>> exp(10)
ans =
2.2026e+004
Creating Arrays
MATLAB variables are arrays of numbers. An
array consisting of one element is called a
scalar. For example;
x =2
More commonly, x will assume a number of
values, For example;
x = 0:0.5:5
x = [0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5,
5.0]
Creating special arrays
ones(n,m)
a n-by-m double array, each entry is equal to 1
zeros(n,m)
a n-by-m double array, each entry is equal to 0
rand(n,m)
a n-by-m double array, each entry is a random number
between 0 and 1.
Examples
>> A = ones(2,3);
>> B = zeros(3,4);
>> C = rand(2,5);
Matrix generation
Matrices are the basic elements of the
MATLAB environment. A matrix is a twodimensional array consisting of m rows and
n columns.
An array of dimension 1xn is called row
vector.
A row vector, whereas an array of
dimension mx1 is called a column vector.
Entering a vector
To enter a row vector, v, type
>> v = [1 4 7 10 13]
v=
1 4 7 10 13
To enter a column vector, w, type
>> w = [1;4;7;10;13]
w=
1
4
7
10
13
Transpose operation
>> w = v'
w=
1
4
7
10
13
To access blocks of elements
>> v(1:3)
ans =
1 4 7
All elements from the third through the last
elements,
>> v(3,end)
ans =
7 10 13
cont
If v is a vector, writing
>> v(:)
produces a column vector
whereas writing
>> v(1:end)
produces a row vector.
Entering a matrix
A matrix is an array of numbers. To type a
matrix into MATLAB you must
begin with a square bracket, [
separate elements in a row with spaces or
commas (,)
use a semicolon (;) to separate rows
end the matrix with another square
bracket, ].
To enter a matrix A, such as,
A=
123
456
789
type,
>> A = [1 2 3; 4 5 6; 7 8 9]
MATLAB then displays the 3 x 3 matrix as follows,
A=
123
456
789
cont
We can then view a particular element in
a matrix by specifying its location. We write,
>> A(2,1)
ans =
4
A(2,1) is an element located in the second
row and first column. Its value is 4.
Matrix indexing
We select elements in a matrix just as we did for vectors, but
now we need two indices. The element of row i and column j
of the matrix A is denoted by A(i,j). Thus, A(i,j) refers to the
element Aij of matrix A. The first index is the row number and
the second index is the column number. For example, A(1,3)
is an element of first row and third column. Here, A(1,3)=3.
Correcting any entry is easy through indexing. Here we
substitute A(3,3)=9 by A(3,3)=0. The result is
>> A(3,3) = 0
A=
123
456
780
Colon operator in a matrix
The colon operator can also be used to pick
out a certain row or column. For example,
the statement A(m:n,k:l specifies rows m to
n and column k to l).
For example,
>> A(2,:)
ans =
4 5 6
is the second row elements of A.
cont
The colon operator can also be used to extract
a sub-matrix from a matrix A.
>> A(:,2:3)
ans =
23
56
80
A(:,2:3) is a sub-matrix with the last two
columns of A.
cont
A row or a column of a matrix can be
deleted by setting it to a null vector, [ ].
>> A(:,2)=[]
ans =
1 3
4 6
7 0
Creating a sub-matrix
To extract a sub matrix B consisting of rows
2 and 3 and columns 1 and 2 of the matrix
A, do the following
>> B = A([2 3],[1 2])
B=
4 5
7 8
To interchange rows 1 and 2 of A, use the
vector of row indices together with the
colon operator.
>> C = A([2 1 3],:)
C=
4 5 6
1 2 3
7 8 0
It is important to note that the colon operator (:)
stands for all columns or all rows. To create a vector
version of matrix A, do the following
>> A(:)
ans =
1
2
3
4
5
6
7
8
0
Restoring the matrix
To delete a row or column of a matrix, use the empty vector
operator, [ ].
>> A(3,:) = []
A=
1 2 3
4 5 6
To restore the third row, we use a technique for creating a
matrix
>> A = [A(1,:);A(2,:);[7 8 0]]
A=
1 2 3
4 5 6
7 8 0
Dimensions of a matrix
>> size(A)
ans =
3 3
means 3 rows and 3 columns.
Or more explicitly with,
>> [m,n]=size(A)
Concatenating matrices
For example,
>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]
B=
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1
0
0
-4 -5 -6 0 1
0
-7 -8 -9 0 0
1
Matrix generators
Elementary
matrices
Examples
>> b=ones(3,1)
b=
1
1
1
Equivalently, we can define b as >> b=[1;1;1]
>> eye(3)
ans =
100
010
001
>> c=zeros(2,3)
c=
000
000
matrices can be constructed in a block form.
With C defined by C = [1 2; 3 4], we may create
a matrix D as follows
>> D = [C zeros(2); ones(2) eye(2)]
D=
1 2 0 0
3 4 0 0
1 1 1 0
1 1 0 1
Matrix arithmetic operations
A+B or B+A : valid if A and B are of the
same size
A*B : valid if A's number of column equals
B's number of rows
A^2 : valid if A is square and equals A*A
*A or A* : multiplies each element of A
by
Array arithmetic operations
Cont
Matrix inverse
Let's consider the same matrix A.
A=
123
456
780
>> inv(A)
ans =
-1.7778 0.8889 -0.1111
1.5556
-0.7778 0.2222
-0.1111
0.2222 -0.1111
>> det(A)
ans =
27
Solving linear equations
For
example,
Cont
Example
solve for x in the equation x-5 = 0
y = solve('x-5 = 0')
Y=5
In general, solve(equation, variable)
For example,
solve the equation v u 3t2= 0, for v.
ans = 3*t^2 + u
Programming in MATLAB
Basic plotting
MATLAB has an excellent set of graphic
tools.
Plotting a given data set or the results of
computation is possible with very few
commands.
Creating simple plots
For example in 2D, is to take a vector of x-
coordinates, x = (x1; : : : ; xN), and a vector of
y-coordinates, y = (y1; : : : ; yN), locate the
points (xi; yi), with i = 1; 2; : : : ; n and then join
them by straight lines. You need to prepare x
and y in an identical array form; namely, x and
y are both row arrays or column arrays of the
same length.
Cont
The MATLAB command to plot a graph is
plot(x,y).
The vectors x = (1; 2; 3; 4; 5; 6) and y =
(3;1; 2; 4; 5; 1)
>>
>>
>>
>>
x = [1 2 3 4 5 6];
y = [3 -1 2 4 5 1];
plot(x,y)
grid on
Cont
To plot the function sin (x) on the interval [0;
2], we first create a vector of
x values
ranging from 0 to 2, then compute the sine of
these values, and finally plot the result:
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y)
Adding titles, axis labels, and
annotations
>> xlabel('x = 0:2\pi')
>> ylabel('Sine of x')
>> title('Plot of the Sine function')
The colour of a single curve is, by default,
blue, but other colours are possible. The
desired colour is indicated by a third
argument. For example, red is selected by
plot(x,y,'r').
Specifying line styles and
colours
plot(x,y,'style_color_marker')
Multiple data sets in one plot
Multiple (x; y) pairs arguments create multiple graphs with a
single call to plot.
For example, y1 = 2 cos(x), y2 = cos(x), and y3 = 0:5* cos(x),
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot (x,y1,'--',x,y2,'-',x,y3,':')
xlabel(x = 0:2\pi)
ylabel('Cosine functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Typical example of multiple plots')
axis([0 2*pi -3 3])
Example
Draw the graph of two polynomials
f(x) = 3x4+ 2x3+ 7x2+ 2x + 9 and
g(x) = 5x3+ 9x + 2
Create a script file and type the following code
x = [-10 : 0.01: 10];
y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;
g = 5 * x.^3 + 9 * x + 2;
plot(x, y, 'r', x, g, 'g')
Subplot
>> x = 0:pi/100:2*pi;
>> y1 = 2*cos(x);
>> y2 = cos(x);
>> y3 = 0.5*cos(x);
>> subplot(1,3,1)
>> plot(x,y1)
>> subplot(1,3,2)
>> plot(x,y2)
subplot(1,3,3)
>> plot(x,y3)
Example
Generate two plots in a single figure with labelling of axis,
y = e1.5xsin(10x)
y = e2xsin(10x)
Create a script file and type the following code
x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,1)
plot(x,y),
xlabel('x'),
ylabel('exp(1.5x)*sin(10x)'),
axis([0 5 -1 1])
y = exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),
xlabel('x'),
ylabel('exp(2x)*sin(10x)'),
axis([0 5 -1 1])
Create a Stem Plot
>>
>>
>>
>>
t = 0:.2:20;
alpha =.055;
Y=exp(-alpha*t).*sin(5*t)
stem(t,y)
3-D Plot
Create a 3D surface map for the function g = xe -(x2+ y2)
[x,y] = meshgrid(-2:.2:2);
g = x .* exp(-x.^2 - y.^2);
surf(x, y, g)
Themeshgridcommand is used for generating a
matrix of elements that give the range over x and y
along with the specification of increment in each case.
Introduction to programming in
MATLAB
So far, all the commands were executed in the
Command Window.
The problem is that the commands entered in the
Command Window cannot be saved and executed
again for several times. Therefore, a different way of
executing repeatedly
commands with MATLAB is:
1. To create a file with a list of commands,
2. save the file, and
3. run the file.
M-File Scripts
A script file is an external file that contains a
sequence of MATLAB statements. Script files
have a filename extension .m and are often
called M-files.
M-files can be scripts that simply execute a
series of MATLAB statements, or they can be
functions that can accept arguments and can
produce one or more outputs.
Example
Consider the system of equations:
Solution
Use the MATLAB editor to create a file:
File
New
M-file
Enter the following statements in the file:
A = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = A\b
Save the file, for example, example1.m.
Run the file
Example 2
Plot the following cosine functions, y1 = 2 cos(x), y2 =
cos(x), and y3 = 0:5*cos(x), in the interval x = 0:2 .
Solution
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,'--',x,y2,'-',x,y3,':')
xlabel('0 \leq x \leq 2\pi')
ylabel('Cosine functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Typical example of multiple plots')
axis([0 2*pi -3 3])
Script side-effects
All variables created in a script file are added to the
workspace. This may have undesirable effects,
because:
Variables already existing in the workspace may be
overwritten.
The execution of the script can be affected by the
state variables in the workspace.
As a result, because scripts have some undesirable
side-effects, it is better to code any complicated
applications using rather function M-file.
M-File functions
As mentioned earlier, functions are
programs (or routines) that accept input
arguments and return output arguments.
Each M-file function has its own area of
workspace, separated from the MATLAB
base workspace.
Anatomy of a M-File function
This simple function shows the basic parts of an M-
file.
function f = factorial(n)
(1)
% FACTORIAL(N) returns the factorial of N.
% Compute a factorial value.
f = prod(1:n); (4)
..(2)
(3)
The first line of a function M-file starts with the
keyword function. It gives the function name and
order of arguments.
Cont
As an example, for n = 5, the result is,
>> f = factorial(5)
f=
120
It is important to note that function name must
begin with a letter, and must be no longer than
the maximum of 63 characters.
The name of the text file that you save will consist
of the function name with the extension .m. Thus,
the above example file would be factorial.m.
Anatomy of a M-File function
Difference between Scripts and
Functions
Example
Create a function that find maximum of the five
numbers
function max = mymax(n1, n2, n3, n4, n5)
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
End
if(n5 > max)
max = n5;
end
Input to a script file
When a script file is executed, the variables
that are used in the calculations within the
file must have assigned values. The
assignment of a value to a variable can be
done in three ways.
1. The variable is defined in the script file.
2. The variable is defined in the command
prompt.
3. The variable is entered when the script is
executed.
Cont
When the file is executed, the user is prompted to
assign a value to the variable in the command
prompt. This is done by using the input command.
Example
calculate the average of points scored
in three games.
game1 = input('Enter the points scored in
the
first game ');
game2 = input('Enter the points scored in
the
second game ');
game3 = input('Enter the points scored in
the
third game ');
average = (game1+game2+game3)/3
The following shows the command prompt
when this script file is executed.
>> Enter the points scored in the first game 15
>> Enter the points scored in the second game
23
>> Enter the points scored in the third game 10
average =
16
Exercise
1. write a function that would calculate the roots of a quadratic equation.
The function would take three inputs, the quadratic co-efficient, the
linear co-efficient and the constant term. It would return the roots.
function [x1,x2] = quadratic(a,b,c)
%this function returns the roots of a quadratic equation.
% It takes 3 input arguments % which are the co-efficients of x2, x and the
constant term
% It returns the roots
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic
Function d = disc(a,b,c) %function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end
% end of sub-function
Data Import
load and display an image file
filename = xyz.jpg';
A = importdata(filename);
image(A);
Saving output to a file
The command fprintf can be used for writing the
output to a file. The saved data can
subsequently be used by MATLAB or other
softwares.
To save the results of some computation to a file
in a text format requires the following steps:
1. Open a file using fopen
2. Write the output using fprintf
3. Close the file using fclose
Example
% write some variable length strings to a file
op = fopen('weekdays.txt','wt');
fprintf(op,'Sunday\nMonday\nTuesday\nWe
dnesday\n');
fprintf(op,'Thursday\nFriday\nSaturday\n');
fclose(op);
Example
% create a matrix y, with two rows
x=0:10:100;
y = [x; log(x)];
% open a file for writing
fid = fopen('logtable.txt', 'w');
% Table Header
fprintf(fid, 'Log
Function\n\n');
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f %f\n', y);
fclose(fid);
% display the file created
type logtable.txt
Control flow and operators
Like other computer programming languages,
MATLAB has some decision making structures for
control of command execution. These decision
making or control flow structures include for loops,
while loops, and if-else-end constructions.
Control flow
MATLAB has four control flow structures
if statement
for loop
while loop
switch statement.
The ``if...end'' structure
MATLAB supports the variants of if " construct.
if ... end
if ... else ... end
if ... elseif ... else ... End
The simplest form of the if statement is
if expression
statements
end
Examples
1. discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots are
imaginary');
end
2. discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots are
imaginary');
else
disp('Roots are real, but may be repeated')
end
3. discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots
are
imaginary');
elseif discr == 0
disp('Discriminant is zero, roots are repeated');
else
disp('Roots are real');
end
Notes
elseif has no space between else and if
(one word)
No semicolon (;) is needed at the end of
lines containing if, else, end
Indentation of if block is not required, but
facilitate the reading.
The end statement is required
Relational and logical
operators
A relational operator compares two numbers by
determining whether a comparison is true or false.
The ``for...end'' loop
for variable = expression
statements
End
A simple example of for loop is
for ii=1:5
x=ii*ii
end
Multiple for loops
The following statements form the 5-by-5
symmetric matrix A with (i; j) element i/j
n = 5; A = eye(n);
for j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end
The ``while...end'' loop
This loop is used when the number of passes is not specified. The
looping continues until a stated condition is satisfied. The while
loop has the form:
while expression
statements
End
The statements are executed as long as expression is true.
x=1
while x <= 10
x = 3*x
end
Other flow structures
The break statement. A while loop can be terminated
with the break statement, which passes control to the
first statement after the corresponding end. The
break statement can also be used to exit a for loop.
The continue statement can also be used to exit a for
loop to pass immediately to the next iteration of the
loop, skipping the remaining statements in the loop.
Other control statements include return, switch, etc.
Debugging M-files
Debugging is the process by which you isolate and
fix errors in your program or code.
Debugging helps to correct two kind of errors:
1. Syntax errors - omitting a parenthesis or
misspelling a function name
2. Run-time errors - Run-time errors are usually
apparent and difficult to track down. They
produce unexpected results.
Debugging process
We can debug the M-files using the Editor/Debugger as well
as using debugging functions from the Command Window.
The debugging process consists of
Preparing for debugging
Setting breakpoints
Running an M-file with breakpoints
Stepping through an M-file
Examining values
Correcting problems
Ending debugging
Preparing for debugging
Here we use the Editor/Debugger for
debugging. Do the following to prepare for
debugging:
Open the file
Save changes
Be sure the file you run and any files it calls
are in the directories that are on the search
path.
Setting breakpoints
Set breakpoints to pause execution of the function.
There are three basic types of breakpoints:
A standard breakpoint, which stops at a specified line.
A conditional breakpoint, which stops at a specified
line and under specified conditions.
An error breakpoint that stops when it produces the
specified type of warning, error, NaN, or infinite value.
You cannot set breakpoints while MATLAB is busy, for
example, running an M-file.
Running with breakpoints
After setting breakpoints, run the M-file.
Running the M-file results in the following:
The prompt in the Command Window changes to
K>>
Indicating that MATLAB is in debug mode.
The program pauses at the first breakpoint. This
means that line will be executed when you continue.
The pause is indicated by the green arrow.
In breakpoint, we can examine variable, step
through programs, and run other calling functions.
Examining values
While the program is paused, we can view the value of any
variable currently in the workspace. Examine values when we
want to see whether a line of code has produced the
expected result or not. If the result is as expected, step to the
next line, and continue running. If the result is not as
expected, then that line, or the previous line, contains an
error.
Viewing values as datatips
First, we position the cursor to the left of a variable on that
line. Its current value appears. This is called a datatip, which
is like a tooltip for data. If you have trouble getting the
datatip to appear, click in the line and then move the cursor
next to the variable.
Correcting and ending
debugging
While debugging, we can change the value
of a variable to see if the new value
produces expected results. While the
program is paused, assign a new value to
the variable in the Command Window,
Workspace browser, or Array Editor. Then
continue running and stepping through the
program.
Ending debugging
After
identifying a problem, end the
debugging session. It is best to quit debug
mode before editing an M-file. Otherwise,
you can get unexpected results when you
run the file. To end debugging, select Exit
Debug Mode from the Debug menu.
Correcting an M-file
To correct errors in an M-file,
Quit debugging
Do not make changes to an M-file while
MATLAB is in debug mode
Make changes to the M-file
Save the M-file
Clear breakpoints
Run the M-file again to be sure it produces
the expected results.