Introduction To MATLAB (Based On Matlab Manual) : Signal and System Theory II, SS 2011
Introduction To MATLAB (Based On Matlab Manual) : Signal and System Theory II, SS 2011
Introduction To MATLAB (Based On Matlab Manual) : Signal and System Theory II, SS 2011
Lygeros
In case that the desktop does not appear with the default layout, you can change it by the menu
Desktop → Desktop Layout → Default.
1
Use Tab to go to View or change
Workspace current
Get Help Directory
Browser
View or Execute
Enter Matlab
previously run
Functions at
commands from the
command line
Command History
prompt
Window
1.2.2 Editor
MATLAB editor (Figure 2) can be used to create and debug M – files, which are programs you write to
run MATLAB functions. A M – file is a text file that contains a sequence of MATLAB commands; the
2
commands contained in a script file can be run, in order, in the MATLAB command window simply by
typing the name of the file at the command prompt. M – files are very useful when you use a sequence of
commands over and over again, in many different MATLAB sessions and you do not want to manually
type these commands at the command prompt whenever you want to use them.
You can run a script or a function that does not require an input argument directly from the Edi-
tor/Debugger either by pressing F 5 or selecting Run from the Debug menu. If you want to run a part of
the script then you can highlight the part of the script you want to evaluate and then press F 9 to run it.
In all cases the results are shown in Command Window.
3
for MATLAB:
Command Line
• HELP: HELP FUN displays a description of and syntax for the function FUN. (e.g. help plot)
• DOC: DOC FUN displays the HTML documentation for the MATLAB function FUN. (e.g. doc
help)
Help Browser Another source of help is the MATLAB help browser. You can invoke the MATLAB
help browser by typing, helpbrowser, at the MATLAB command prompt, clicking on the help button, or
by selecting Start → M AT LAB → Help from the MATLAB desktop.
1.3 Variables
The simplest way to use MATLAB is for arithmetic operations. The basic arithmetic operators are
+, −, /, ∗ and ∧ (power). These operators can be used in conjunction with brackets (). As with all
programming languages special care should be given on how a mathematic expression is written. For
example, the result of the expression 5 + 10/2 ∗ 3 is 20 and corresponds in the expression 5 + (10/2) ∗ 3
and not in the expression 5 + 10/(2 ∗ 3). Generally, Matlab works according to the priorities:
For example:
3 + 5/2 ∗ 4 − 2∧ 3 + (5 ∗ 2) = 3 + 5/2 ∗ 4 − 2∧ 3 + 10
= 3 + 5/2 ∗ 4 − 8 + 10
= 3 + 2.5 ∗ 4 − 8 + 10
= 3 + 10 − 8 + 10
= 15
MATLAB always stores the result of a calculation in a varable named ans, but it is possible to use
our own names to store numbers:
>> x=5+2^2
x =
>> y=2*x
y =
18
4
These are examples of assignment statements: values are assigned to variables. Each variable
must be assigned a value before it may be used on the right of an assignment statement.
One often does not want to see the result of intermediate calculations. This can be done by terminating
the assignment statement or expression with semi–colon:
>> x=5+2^2;
>> y=2*x;
>> z=x^2+y^2
z =
405
You can also assign pieces of text to variables, not just numbers. You do this using single quotes (not
double quotes — single quotes and double quotes have different uses in MATLAB) around the text you
want to assign to a variable. For example:
>> w = ’Goodmorning’;
>> w
w =
Goodmorning
• Only use primary alphabetic characters (i.e., “A-Z”), numbers, and the underscore character in
your variable names.
• You cannot have any spaces in your variable names, so, for example, using “this is a variable” as a
variable name is not allowed (in general, you can use the underscore character wherever you would
use space to string words together in your variable name).
• MATLAB is case sensitive. What this means for variables is that the same text, with different
mixes of capital and small case letters, will not be the same variables in MATLAB. For example,
“VaRIAbLe”, “variable”, “VARIABLE” and “variablE” would all be considered distinct variables
in MATLAB.
• Exponential function:exp.
5
• Natural logarithm:textttlog.
(1) Decide on a name for the function, making sure that it does not conflict with a name that is already
used by Matlab.
(2) The first line of the file must have the format:
>> [K,L]=avg3(3,5,7)
K =
L =
15
1.5 Matrices
In MATLAB, and in linear algebra, numeric objects can be categorized simply as matrix: Both scalars
and vectors can be considered a special type of matrix. For example a scalar is a matrix with a row
and column dimension of one (1-by-1 matrix). And a vector is a matrix with one row and n columns,
or n rows and one column. Most calculations in MATLAB are done with “matrices”. Hence the name
MATrix LABoratory.
6
1.5.1 Creating Matrices in MATLAB
In MATLAB matrices are defined inside a pair of square brackets ([]). Punctuation marks of a comma
(,), and semicolon (;) are used as a row separator and column separator, respectfully (you can also use a
space as a row separator, and a carriage return (the enter key) as a column separator as well.). Use the
examples below to check how vectors and matrices can be created in MATLAB.
>> A=[1,4,7]
>> B=[1;4;7]
You can also combine different vectors and matrices together to define a new matrix. For example:
>> D=[A A]
>> E=[B B]
>> F=[C C]
>> G=[C;C]
>> C(3,2)
ans =
You can also extract any continuous subset of a matrix, by referring to the row range and column
range you want. In the following examples we extract i) the 3rd column, ii) the 2nd and 3rd columns,
iii) the 4th row, and iv) the central 2 × 2 matrix.
7
>> C(:,3)
>> C(:,2:3)
>> C(4,:)
>> C(2:3,2:3)
• Subtraction: >> C = A − B
• Multiplication: >> C = A ∗ B
• Element-by-element Multiplication: C = A. ∗ B
• Transposing: >> C = A′
• [V, D] = eig(A) produces matrices of eigenvalues (D) and eigenvectors (V ) of matrix A, so that
A ∗ V = V ∗ D. Matrix D is the canonical form of A a diagonal matrix with A’s eigenvalues on
the main diagonal. Matrix V is the modal matrix its columns are the eigenvectors of A.
• The svd command computes the matrix singular value decomposition. s = svd(X) returns a vector
of singular values. [U, S, V ] = svd(X) produces a diagonal matrix S of the same dimension as X,
with nonnegative diagonal elements in decreasing order, and unitary matrices U and V so that
X = U ∗ S ∗ V ′.
1.6 Loops
There are occasions that we want to repeat a segment of code a number of different times. In such cases
it is convenient to use loop structures. In MATLAB there are three loop structures:
• For Loop
The general syntax is:
8
for variable = expression
statement
...
statement
end
The columns of the expression are stored one at a time in the variable while the following statements,
up to the end, are executed.In practice, the expression is almost always of the form scalar:scalar ,
in which case its columns are simply scalars.The scope of the for statement is always terminated
with a matching end.
• While Loop
The general format is
while expression
statement
...
statement
end
while repeats statements an indefinite number of times. The statements are executed while the real
part of expression has all nonzero elements. Expression is usually of the form
expression relation-operator expression
where relation-operator is ==, <, >, <=, >= or =.
if expression1
statements1
elseif expression2
statements2
else
statements3
end
9
ẋ = Ax + Bu
y = Cx + Du
1.7.3 Convertions
• tf 2ss converts the parameters of a transfer function representation of a given system to those of
an equivalent state-space representation.
[A, B, C, D] = tf 2ss(b, a)
returns the A, B, C, and D matrices of a state space representation for the single-input transfer
function
B(s)
H(s) = = C(sI − A)−1 B + D (1)
A(s)
B(s)
H(s) = = C(sI − A)−1 B + D (2)
A(s)
of the system
ẋ = Ax + Bu
y = Cx + Du
10
t = 0 : dt : T f inal
The matrix u must have as many rows as time samples (length(t)) and as many columns as system
inputs. Each row u(i, :) specifies the input value(s) at the time sample t(i).
When invoked with left-hand arguments,
[y, t] = lsim(sys, u, t)
[y, t, x] = lsim(sys, u, t) → for state-space models only
[y, t, x] = lsim(sys, u, t, x0) → with initial state x0
return the output response y, the time vector t used for simulation, and the state trajectories x (for
state-space models only).
There are also Matlab functions for specific type of inputs:
clear all
t_init=0;T_s=0.1;t_fin=40;options=[]; %simulation interval & sampling
row_num=4; %state vector dimension
x_system=zeros(row_num,ceil((t_fin-t_init)/T_s)); %system response
cnt=1; %counter
x_ode=zeros(row_num,1);x_ode(3)=50*pi/180;
x_system(:,1)=x_ode; %initial conditions specifications
for t=t_init:T_s:t_fin-T_s...
cnt=cnt+1;... %counter increment
F_l=0;... %input specification
[t_ode,x_ode]=ode45(’carrierpendulum’,[t
t+T_s],[x_ode],options,F_l);...
szx_ode=size(x_ode);x_ode=x_ode(szx_ode(1),:)’;x_system(:,cnt)=x_ode;...
end figure(1) t=[t_init:T_s:t_fin];
subplot(2,2,1),plot(t,x_system(1,:)),title(’carrier position’)
subplot(2,2,2),plot(t,x_system(2,:)),title(’carrier velocity’)
subplot(2,2,3),plot(t,x_system(3,:)),title(’pendulum angle’)
11
Figure 3: Carrier Pendulum
subplot(2,2,4),plot(t,x_system(4,:)),title(’pendulum angular
velocity’)
1.9 Plots
The most basic plotting command in MATLAB is the plot command. The plot command, when called
with two same-sized vectors X and Y , makes a two-dimensional line plot for each point in X and its
corresponding point in Y : the numbers in X are on the abscissa (x-axis) and the numbers in Y are on
the ordinate (y-axis). In other words, it will draw points at (X(1), Y (1)), (X(2), Y (2)), (X(3), Y (3)), etc.,
and then connect all these points together with lines. For example:
12
>> Y=3.*X;
>> plot(X,Y)
Still another thing you might want to do is to have multiple plots in the same window, but each
in a separate part of the window (i.e., each with their own axes). You can do this using the subplot
command. If you type subplot(M,N,P) at the command prompt, MATLAB will divide the plot window
into a bunch of rectangles — there will be M rows and N columns of rectangles — and MATLAB will
place the result of the next ”plot” command in the Pth rectangle (where the first rectangle is in the upper
left). For example:
>> subplot(3,1,1)
>> plot(X,Y1)
>> subplot(3,1,2)
>> plot(X,Y2)
>> subplot(3,1,3)
>> plot(X,Y3)
13