4. 4
MATLAB Basic
• MATLAB stands for Matrix Laboratory
• By double clicking on MATLAB icon,command window
will appear. A >> prompt will be shown.This is command
prompt
• We can write simple short programs in command window
• To clear the command window type clc command
5. 5
MATLAB Basic
• The MATLAB environment is command oriented
somewhat like UNIX. A prompt appears on the screen
and a MATLAB statement can be entered.
• When the <ENTER> key is pressed, the statement is
executed, and another prompt appears.
• If a statement is terminated with a semicolon ( ; ), no
results will be displayed. Otherwise results will
appear before the next prompt.
6. 6
MATLAB Basic
Command line help
• Typing help at command prompt will generate list of topics
• HELP topics
>> help
Matlabgeneral - general purpose commands
Matlabops -operators and special characters
Matlablang - programming language constructs
Matlab elmat - elementary matrices and matrix manipulation
Matlab elfun - elementary math functions
Matlab specfun –specialised math functions
Matlab matfun - matrix functions-numerical linear algebra
Matlab datafun - data analysis and fourier transforms
……..
For specific help on topic, for example on operators
>>help ops
7. 7
MATLAB Basic
• Toolbox is colletion of functions for a particular
application
• Help toolbox name displays all the functions available in
that toolbox
• For example >>help nnet
displays all the functions available in nueral network
toolbox
8. 8
MATLAB Basic
• lookfor searches all .m files for the keyword
>>lookfor matrix
• Demo
• For demonstration on MATLAB feature, type demo
>>demo
• Will open a new window for demo
9. 9
MATLAB Basic
• Results of computations are saved in variables whose
names are chosen by user
• Variable name begins with a letter, followed by letters,
numbers or underscores.
• Variable names are case sensitive
• Each variable must be assigned a value before it is used on
right side of an assignment statement
>> x=13
y=x+5 y=z+5
y = ??? Undefined function or variable ‘z’
18
• Special names:don’t use pi,inf,nan, etc as variables as their
values are predetermined
10. 10
MATLAB SPECIAL VARIABLES
ans Default variable name for results
pi Value of π
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real
number
realmax The largest usable positive real
number
11. 11
MATLAB Math & Assignment Operators
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or or . ba or b.a
NOTE: 56/8 = 856
Addition + a + b
Subtraction - a -b
Assignment = a = b (assign b to a)
12. 12
Other MATLAB symbols
>> prompt
. . . continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range
14. 14
Vectors & Matrices
• MATLAB treats all variables as matrices. For our purposes
a matrix can be thought of as an array, in fact, that is how
it is stored.
• Vectors are special forms of matrices and contain only one
row OR one column.
• Scalars are matrices with only one row and one column
15. 15
Vectors & Matrices
• A matrix with only one row AND one column is a scalar. A
scalar can be created in MATLAB as follows:
» a_value=23
a_value =
23
16. 16
Vectors & Matrices
• A matrix with only one row is called a row vector. A row
vector can be created in MATLAB as follows (note the
commas):
>> rowvec = [12 , 14 , 63]
or
>> rowvec=[12 14 63]
rowvec =
12 14 63
>>rowvec=1:1:10
rowvec = 1 2 3 4 5 6 7 8 9 10
17. 17
Vectors & Matrices
• A matrix with only one column is called a column vector.
A column vector can be created in MATLAB as follows
(note the semicolons):
>> colvec = [13 ; 45 ; -2]
colvec =
13
45
-2
18. 18
Vectors & Matrices
• Entering matrices into Matlab is the same as entering a
vector, except each row of elements is separated by a
semicolon (;)
» A = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
A =
1 2 3
4 5 6
7 8 9
19. 19
Vectors & Matrices
• A column vector can be
extracted from a matrix.
As an example we create a
matrix below:
» matrix=[1,2,3;4,5,6;7,8,9]
matrix =
1 2 3
4 5 6
7 8 9
Here we extract column 2
of the matrix and make a
column vector:
» col_two=matrix( : , 2)
col_two =
2
5
8
20. 20
Vectors & Matrices
• Transform rows(columns) into rows(columns)
• The ‘(quote) operator create the conjugate transpose of vector(matrix)
>>a=[1 2 3]
>>a’
Ans=
1
2
3
The .’(dot quote) operator create the transpose of a vector(matrix)
>>c=[1+i 2+2*i];
>>c’ >>c.’
ans= ans=
1.0000 -1.0000i 1.0000 + 1.0000i
2.0000 -2.0000i 2.0000+2.0000i
21. 21
Vectors & Matrices
• length:determines the number of components of a vector
>>a=[1 2 3];
>>length(a)
ans=
3
• The . operator is used for component wise application of the operator
that follows the dot operator.
>>a.*a
ans=
1 4 9
>>a.^2
ans=
1 4 9
22. 22
Vectors & Matrices
dot: returns the scalar product of vectors A and B.A & B
must be of same length.
>>a=[1;2;3];
>>b=[-2 1 2];
>>dot(a,b)
ans =
6
cross:returns the cross product vectors A and B. A and B
must be of same length. Length vector must be 3.
>>cross(a,b)
ans=
1 -8 5
23. 23
Vectors & Matrices
• Extracting submatrix
>>a=[1 2 3;4 5 6;7 8 9]
a=
1 2 3
4 5 6
7 8 9
• For example to extract a submatrix b consisting of rows 1&3 and
columns 1&2
>>b=a([1 2],[1 2])
b=
1 2
4 5
( ) indicates address
[ ] indicates numeric value
24. 24
Vectors & Matrices
• To interchange rows(columns)
>> a=[1 2 3;4 5 6;7 8 9];
>> c=a([3 2 1],:) >>d=a(:,[2 1 3])
c = d=
7 8 9 2 1 3
4 5 6 5 4 6
1 2 3 8 7 9
: indicates all rows(columns) in order [1 2 3]
• To delete a row or column, use empty vector operator [ ]
>> a(:,2)=[ ]
A =
1 3
4 6
7 9
25. 25
Vectors & Matrices
• Extracting bits of vector(matrix)
• ( ) (bracket/brace) is used to extract bit/s of a specific
position/s
>>a=[1 2 3;4 5 6;7 8 9];
>>a(3,2)
ans:
8
26. 26
Vectors & Matrices
• Inserting a new row(column)
>> a=[1 3;4 6;7 9]; >>a=[1 3;4 6;7 9]
a=[a(:,1) [2 5 8]’ a(:,2)] a=[a(1,:);a(2,:) [5 6]’ a(3,:)]
a = a =
1 2 3 1 3
4 5 6 4 6
7 8 9 5 6
7 9
• The .(dot) operator also works for matrices
>> a=[1 2 3;3 2 1]’
a.*a
ans =
1 4 9
9 4 1
27. 27
Vectors & Matrices
• Size of a matrix:
size get the size(dimension of the matrix)
>>a=[1 2 3;4 5 6;7 8 9];
>>size(a)
ans =
3 3
• Matrix concatenation
• Large matrix can be built from smaller matrices
>> a=[0 1;3 -2;4 2]
>> b=[8;-4;1]
>>c = [a b]
c =
0 1 8
3 -2 -4
4 2 1
28. 28
vectors & matrices
• Special matrices
• ones(m,n) gives an mxn matrix of 1’s
>>a=ones(2,3)
a=
1 1 1
1 1 1
• zero(m,n) gives an mxn matrix of 0’s
>>b=zeros(3,3)
b=
0 0 0
0 0 0
0 0 0
• eye(m) gives an mxm identity matrix
>>I=eye(3)
I =
1 0 0
0 1 0
0 0 1
29. 29
Vectors & Matrices
• Matrix multiplication
No. of columns of A must be equal to no. of rows in B
>>A=[1 2 3;3 2 1];
B=[2 4;6 8;3 9]
A*B
ans =
23 47
21 37
30. 30
Vectors & Matrices
• Diagonal matrix:
• Given a vector diag creates a matrix with that vector as main diagonal
>> a=[1 2 3]
b=diag(a)
b=
1 0 0
0 2 0
0 0 3
• Main diagonal of matrix :
• Given a matrix diag creates main diagonal vector of that matrix
>>a=[1 2 3;4 5 6;7 8 9];
b=diag(a)
b =
1
5
9
31. 31
Saving and loading variables
• Save
• Save workspace variables on disk
• As an alternative to the save function, select Save
Workspace As from the File menu in the MATLAB
desktop
32. 32
Saving and loading variables
>>save
save by itself, stores all workspace variables in a
binary format in the current directory in a file
named matlab.mat
>>save filename
stores all workspace variables in the current
directory in filename.mat
>> save filename var1 var2 ...
saves only the specified workspace variables in
filename.mat
33. 33
Saving and loading variables
• The load command requires that the data in the file be
organized into a rectangular array. No column titles are
permitted.
• One useful form of the load command is load name.ext
• The following MATLAB statements will load this data into
the matrix ``my_xy'', and then copy it into two vectors, x
and y.
>> load my_xy.dat;
>> x = my_xy(:,1);
>> y = my_xy(:,2);
37. 37
2-D plotting - Line charactrristics
specifier Line colour specifier Marker style
r red . point
b buel o circle
c cyan x x mark
m magneta + plus
y yellow * star
k black s square
w white d diamond
g green v Triangle down
Specifier Line style ^ Triangle up
- solid < Triangle left
: dotted > Triangle right
-. dashdot p pentagram
-- dashed h hexagram
39. 39
2-D plotting
• To put title to the plot
>> title(‘figure title’)
• To label axis
>>xlabel(‘x-axis’) >>ylabel(‘y-axis’)
• To put legend
>> legend(‘data1’,’data2’,…)
• To add a dotted grid
>>grid on
40. 40
2-D plotting - Overlay plots
• Overlay plots can be obtained in two ways
– using plot command
– using hold command
using plot command
plot(x1,y1,x2,y2,….)
uisng hold command
plot(x1,y1)
hold on
plot(x2,y2)
hold off
41. 41
2-D plotting - Overlay plots
• Example
>>x=0:0.1:2
y=sin(pi*x);
z=cos(pi*x);
plot(x,y,’b*’,x,z,’ro’);
title(‘sine&cosine wave’)
xlabel(‘x-axis’),ylabel(‘y-
axis’)
legend(‘sine’,’cosine’)
grid on
42. 42
2-D plotting - Overlay plots
Example
>>x=0:0.1:2
y=sin(pi*x);
z=cos(pi*x);
plot(x,y,’b*’)
hold on
plot(x,z,’ro’)
hold off
title(‘sine&cosine wave’)
xlabel(‘x-axis’),ylabel(‘y-axis’)
legend(‘sine’,’cosine’)
grid on
43. 43
2-D plotting - subplots
• subplot(m,n,p), or subplot(mnp), breaks the Figure
window into an m-by-n matrix of small axes, selects the
p-th axes for the current plot.
• The axes are counted along the top row of the Figure
window, then the second row, etc
>> x=[1 2 3 4];
subplot(2,1,1); plot(x)
subplot(2,1,2); plot(x+2)
44. 44
Plotting
• However figure properties and Axis properties can also be
modified from figure edit menu
• To copy to word and other applications
• From figure edit menu, choose copy figure.
• Go to word or other applications and paste where
required
46. 46
3-D PLOTTING
• Plot3 command
z = 0:0.1:10*pi;
x = exp(-z/20).*cos(z);
y = exp(-z/20).*sin(z);
plot3(x,y,z,'LineWidth',2)
grid on
xlabel('x')
ylabel('y')
zlabel('z')
47. 47
3-D PLOTTING
>> x = (0:2*pi/20:2*pi)';
>> y = (0:4*pi/40:4*pi)';
>> [X,Y] =meshgrid(x,y);
>> z = cos(X).*cos(2*Y);
>> mesh(X,Y,z)
>> surf(X,Y,z)
>>contour(X,Y,z)
• The effect of meshgrid is to create a vector X with the x-grid along
each row, and a vector Y with the y-grid along each column. Then,
using vectorized functions and/or operators, it is easy to evaluate a
function z = f(x,y) of two variables on the rectangular grid:
• The difference is that surf shades the surface, while mesh does not
49. 49
SCRIPT FILES
• A MATLAB script file is a text file that contains one or
more MATLAB commands and, optionally, comments.
• The file is saved with the extension ".m".
• When the filename (without the extension) is issued as a
command in MATLAB, the file is opened, read, and the
commands are executed as if input from the keyboard.
The result is similar to running a program in C.
50. 50
SCRIPT FILES
% This is a MATLAB script file.
% It has been saved as “g13.m“
voltage = [1 2 3 4]
time = .005*[1:length(voltage)]; %Create time vector
plot (time, voltage) %Plot volts vs time
xlabel ('Time in Seconds') % Label x axis
ylabel ('Voltage') % Label y axis
grid on %Put a grid on graph
51. 51
SCRIPT FILES
• The preceding file is executed by issuing a MATLAB command: >>
g13
• This single command causes MATLAB to look in the current
directory, and if a file g13.m is found, open it and execute all of the
commands.
• If MATLAB cannot find the file in the current working directory, an
error message will appear.
• When the file is not in the current working directory, a cd or chdir
command may be issued to change the directory.
52. 52
Function Files
• A MATLAB function file (called an M-file) is a text file that contains a
MATLAB function and, optionally, comments.
• The file is saved with the function name and the usual MATLAB script file
extension, ".m".
• A MATLAB function may be called from the command line or from any other
M-file.
• When the function is called in MATLAB, the file is accessed, the function is
executed, and control is returned to the MATLAB workspace.
• Since the function is not part of the MATLAB workspace, its variables and
their values are not known after control is returned.
• Any values to be returned must be specified in the function syntax.
53. 53
MATLAB Function Files
• The syntax for a MATLAB function definition is:
function [val1, … , valn] = myfunc (arg1, … , argk)
where val1 through valn are the specified returned values from the
function and arg1 through argk are the values sent to the function.
• Since variables are local in MATLAB (as they are in C), the function
has its own memory locations for all of the variables and only the
values (not their addresses) are passed between the MATLAB
workspace and the function.
• It is OK to use the same variable names in the returned value list as in
the argument. The effect is to assign new values to those variables.
As an example, the following slide shows a function that swaps two
values.
54. 54
Example of a MATLAB Function File
function [ a , b ] = swap ( a , b )
% The function swap receives two values, swaps them,
% and returns the result. The syntax for the call is
% [a, b] = swap (a, b) where the a and b in the ( ) are the
% values sent to the function and the a and b in the [ ] are
% returned values which are assigned to corresponding
% variables in your program.
temp=a;
a=b;
b=temp;
55. 55
Example of MATLAB Function Files
• To use the function a MATLAB program could assign
values to two variables (the names do not have to be a and
b) and then call the function to swap them. For instance the
MATLAB commands:
>> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y )
result in:
x =
6
y =
5
56. 56
MATLAB Function Files
• Referring to the function, the comments immediately
following the function definition statement are the "help"
for the function. The MATLAB command:
>>help swap %displays:
The function swap receives two values, swaps them,
and returns the result. The syntax for the call is
[a, b] = swap (a, b) where the a and b in the ( ) are the
values sent to the function and the a and b in the [ ] are
returned values which are assigned to corresponding
variables in your program.
57. 57
MATLAB Function Files
• The MATLAB function must be in the current working directory. If it
is not, the directory must be changed before calling the function.
• If MATLAB cannot find the function or its syntax does not match the
function call, an error message will appear. Failure to change
directories often results in the error message:
Undefined function or improper matrix assignment
• When the function file is not in the current working directory, a cd or
chdir command may be issued to change the directory.
58. 58
MATLAB Function Files
• Unlike C, a MATLAB variable does not have to be
declared before being used, and its data type can be
changed by assigning a new value to it.
• For example, the function factorial ( ) on the next slide
returns an integer when a positive value is sent to it as an
argument, but returns a character string if the argument is
negative.
59. 59
MATLAB Function Files
function [n] = factorial (k)
% The function [n] = factorial(k) calculates and
% returns the value of k factorial. If k is negative,
% an error message is returned.
if (k < 0) n = 'Error, negative argument';
elseif k<2 n=1;
else
n = 1;
for j = [2:k] n = n * j; end
end
60. 60
Control flow
• In matlab there are 5 control statements
• for loops
• while loops
• if-else-end constructions
• switch-case constructions
• break statements
61. 61
Control flow-for loop
• for loops
structure
for k=array
commands
end
• Example
>>sum=0
for i=0:1:100
sum=sum+i;
end
>>sum
sum =
5050
62. 62
Control flow-while loop
• While loops
• Structure
while expression
statements
end
• Example
>>q=pi
while q > 0.01
q=q/2
end
>>q
q=
0.0061
63. 63
Control flow if-else
• If-else-end constructions:
• Structure
if expression
statements
else if expression
statements
:
else
statements
end
• Example
if((attd>=0.9)&(avg>=60))
pass=1;
else
display(‘failed’)
end
64. 64
Control flow switch
• Switch-case construction
• Structure
switch expression
case value1
statements
case value2
statements
:
otherwise
statements
end
• Example
switch gpa
case (4)
disp(‘grade a’)
case(3)
disp(‘grade b’)
case(2)
disp(‘grade c’)
otherwise
disp(‘failed’)
end
65. 65
Control flow - Break
• Break statements
• Break statement lets early exit
from for or while loop.In case
of nested loops,break exit only
from the innermost loop
• Example
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x
67. 67
SIMULINK
• Simulink is a software package for modeling, simulating,
and analyzing dynamical systems. It supports linear and
nonlinear systems, modeled in continuous time, sampled
time, or a hybrid of the two.
• For modeling, Simulink provides a graphical user interface
(GUI) for building models as block diagrams, using click-
and-drag mouse operations.
• With this interface, the models can be drawn
68. 68
SIMULINK
• Simulink includes a comprehensive block library of sinks,
sources, linear and nonlinear components, and connectors.
• You can also customize and create your own blocks.
69. 69
Creating a model
• To start Simulink, you must first start MATLAB.
• You can then start Simulink in two ways:
• Enter the simulink command at the MATLAB
prompt.
• Click on the Simulink icon on the MATLAB
toolbar.
70. 70
Creating a model
• starting Simulink displays
the Simulink Library
Browser
• The Simulink library
window displays icons
representing the block
libraries that come with
Simulink.
• You can create models by
copying blocks from the
library into a model
window.
71. 71
Creating a subsystem
• Subsystem can be created by two methods
– Creating a Subsystem by Adding the Subsystem
Block
– Creating a Subsystem by Grouping Existing Blocks
72. 72
Creating a Subsystem by Adding the
Subsystem Block
• To create a subsystem before adding the blocks it contains, add a
Subsystem block to the model, then add the blocks that make up the
subsystem:
– Copy the Subsystem block from the Signals & Systems library into your
model.
– Open the Subsystem block by double-clicking on it.
– In the empty Subsystem window, create the subsystem.
– Use Inport blocks to represent input from outside the subsystem and
Outport blocks to represent external output.
• For example, the subsystem below includes a Sum block and Inport
and Outport blocks to represent input to and output from the
subsystem:
73. 73
Creating a Subsystem by Grouping Existing
Blocks
• If your model already contains the blocks you want to
convert to a subsystem, you can create the subsystem by
grouping those blocks:
• Enclose the blocks and connecting lines that you want to
include in the subsystem within a bounding box.
• Choose Create Subsystem from the Edit menu. Simulink
replaces the selected blocks with a Subsystem block.
74. 74
Running and stopping simulation
• The model can be run by either typing the model
name(filename) at the command prompt of MATLAB or
by clicking start from simulation menu in the simulink
• To stop a simulation, choose Stop from the Simulation
menu.
• The keyboard shortcut for stopping a simulation is Ctrl-T,
the same as for starting a simulation.
75. 75
Creating custom blocks
• To create custom block first write the function file of the
particular task
• Drag the matlab function block from Functions and Tables
Library from simulink library browser to the working
model area
• Double click on the matlab function block and wirte the
function name in that.
• Now this block can be connected to any other block
76. 76
Creating custom blocks
• For example the following
function called ‘timestwo’
multiplies the input by
two and outputs the
doubled input
function [b] = timestwo(a)
b=2*a;
• This function is
specified in the matlab
function and simulated
by giving a sinusoidal
input
77. 77
S-functions
• An S-function is a computer language description of a
dynamic system.
• S-functions are incorporated into Simulink models by
using the S-Function block in the Functions &Tables
sublibrary.
• the S-Function block’s dialog box is used to specify the
name of the underlying S-function,
78. 78
S-functions
• An M-file S-function consists of a MATLAB function of
the following form:
[sys,x0,str,ts]=f(t,x,u,flag,p1,p2,...)
• where f is the S-function's name, t is the current time, x is
the state vector of the corresponding S-function block, u is
the block's inputs, flag indicates a task to be performed,
and p1, p2, ... are the block's parameters
• During simulation of a model, Simulink repeatedly
invokes f, using flag to indicate the task to be performed
for a particular invocation
79. 79
S-functions
• A template implementation of an M-file S-function,
sfuntmpl.m, resides in
matlabroot/toolbox/simulink/blocks.
• The template consists of a top-level function and a set of
skeleton subfunctions, each of which corresponds to a
particular value of flag.
• The top-level function invokes the subfunction indicated
by flag. The subfunctions, called S-function callback
methods, perform the tasks required of the S-function
during simulation.
80. 80
• The following table lists the contents of an M-file S-function that
follows this standard format.
Simulation Stage S-Function Routine Flag
Initialization mdlInitializeSizes flag = 0
Calculation of outputs mdlOutputs flag = 3
Calculation of derivatives mdlDerivatives flag = 1
End of simulation tasks mdlTerminate flag = 9
81. 81
S-functions
• T he following diagram shows implemetation of S-
function block
• It implements an function example_sfunction written as
a .m file