Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Getting Help

There are three ways to get help in MATLAB. The preferred method is to use the Help
Browser. The Help Browser can be started by selecting the (?) icon from the desktop
toolbar, or by typing helpdesk or helpwin in the Command Window. The Help Browser
is shown in Figure below.

There are also two command-line oriented ways to get help. The first way is to type help
or help followed by a function name in the Command Window. The second way to get
help is the lookfor command. The lookfor command differs from the help command in
that the help command searches for an exact function name match, while the lookfor
command searches the quick summary information in each function for a match. This
makes lookfor slower than help, but it improves the chances of getting back useful
information.
Example: Look for a function to take the inverse of a matrix. Try commands “help
inverse” and “lookfor inverse”.

Initializing Variables in MATLAB


The simplest way to initialize a variable is to assign it one or more values in an
assignment statement. An assignment statement has the general form

var = expression
where var is the name of a variable, and expression is a scalar constant, an array, or
combination of constants, other variables, and mathematical operations (+, -, etc). The
value of the expression is calculated using the normal rules of mathematics, and the
resulting values are stored in named variable.
Example: Type, “var=40i”, “var2=var/5”; “array=[1 2 3 4];”, “x=1;”, “y=4;” and
then “whos array”, “whos”.

The whos command displays a list of all the variables in the Matlab Workspace along
with their size and the number of rows and columns, but it does not show the values of
the variables. To see the value of a variable, simply type the name of the variable and
press ENTER.

Matrices and Vectors


Define a Matrix or Vector
Define a matrix A
A = [ 1 2; 3 4]
A=

1 2
3 4

Define a row vector b


b = [1 2 3 4]
b=

1 2 3 4

Transpose it to a column vector -- use '


b = [1 2 3 4]'
b=

1
2
3
4

Range operator ":"


The range operator allows one to set up a vector of equally spaced entries. Defining
vectors with the range operator
x = 1:4
x=
1 2 3 4

x = 1:2:6
x=

1 3 5

Special matrices
A matrix of all zeros
A = zeros(4,2)
A=

0 0
0 0
0 0
0 0

A matrix of all ones


A = ones(4)
A=

1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

An identity matrix
A = eye(4)
A=

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

Vector and Matrix Operations


The basic arithmetic operations +, -, *, / can be used for vectors and matrices. These
would generate corresponding output vectors or matrices. For example, to add two
vectors:  
a = [1 2 3 4];
b = [5 6 7 8];

c = a+b
c=
6 8 19 12

Matrix multiplication using the * symbol is possible only if the number of columns in the
first matrix equals the number of rows in the second:
a=[1 2 3; 4 5 6]
a=
1 2 3
4 5 6
b = a'
b=
1 4
2 5
3 6
c=a*b
c=
14 32
32 77

However, if you want to multiply corresponding elements of two matrices, then you do
an array multiply using the .* symbol.
a = [1 2 3 4; 5 6 7 8]; b=[2 2 2 2; 3 3 3 3];
c=a .* b
c=
2 4 6 8
15 18 21 24

If a matrix is non-singular, we can compute its inverse


A = [1 2 3; 1 3 4; 1 4 3], invA=inv(A)
A=
123
134
143
invA =
3.5000 -3.0000 0.5000
-0.5000 0 0.5000
-0.5000 1.0000 -0.5000
Solution of Simultaneous Equations with Matrices
Given the system of equations
2x1+3x2+x3 = 9
x1+2x2+3x3 = 6
3x1+x2+2x3 = 8

compute the unknowns x1, x2, and x3 using the inverse matrix method.
A=[2 3 1; 1 2 3; 3 1 2]; B=[9 6 8]'; X=inv(A) * B
X=
1.9444
1.6111
0.2778

Complex Numbers
A complex number z consists of the “real part” x and the “imaginary part” y and is
expressed as
z = x + jy

In Matlab, i and j are variable names that default to the imaginary number. A general
complex number can be formed in three ways:
z = 1 + j*2
z=
1.0000+ 2.0000i
z = 1 + 2j
z=
1.0000+ 2.0000i
z = complex(1,2)
z=
1.0000 + 2.0000i

In Matlab, the function real(z) returns the real part and imag(z) returns the imaginary
part:
z = 3 + 4j
z=
3.0000+ 4.0000i
x = real(z)
x=
3
y = imag(z)
y=
4
The conjugate of a complex number is given by the command conj(z)

z = 3 + 4j
z=

3.0000 + 4.0000i

conj(z)
ans =

3.0000 - 4.0000i

We call z = x + jy the Cartesian or rectangular representation of z, with real component x


and
imaginary component y. We say that the Cartesian pair (x, y) codes the complex number
z. Defining the radius r and the angle θ of the complex number z can be represented in
polar form. For example,
z = 3 + 4j;
r = abs(z)
r=
5
theta = angle(z)
theta =
0.9273

Recall that angles in Matlab are given in radians. To compute the angle in degrees, the
result in radians must be multiplied by (360/2π) or (180/π):
theta = (180/pi)*angle(z)
theta =
53.1301

POL2CART Transform polar to Cartesian coordinates.


[X,Y] = POL2CART(TH,R)

transforms corresponding elements of data stored in polar coordinates (angle TH, radius
R) to Cartesian coordinates X,Y. The arrays TH and R must the same size (or either can
be scalar). TH must be in radians.

CART2POL Transform Cartesian to polar coordinates.


[TH,R] = CART2POL(X,Y)
transforms corresponding elements of data stored in Cartesian coordinates X,Y to polar
coordinates (angle TH and radius R). The arrays X and Y must be the same size (or
either can be scalar). TH is returned in radians.

Loops
A loop is a structure that allows a group of commands to be repeated.

for Loop
A for loop repeats a group of commands a fixed, predetermined number of times. A for
loop has the following structure:
for variable=expression
commands
end
The commands between the for and end statements are executed once for every column
in the expression, beginning with the first column and stepping through to the last
column. At each step, known as an iteration, the appropriate column of the expression is
assigned to the variable. To illustrate the operation of a for loop, we will use a for loop to
calculate the factorial function. The factorial function is defined as
N! = 1, for N=0
N! = N * (N-1) * (N-2) *…* 3 * 2 * 1, for N>0

The MATLAB code to calculate N factorial for positive value of N would be


n_factorial = 1
for ii = 1:n
n_factorial = n_factorial * ii;
end

Suppose that we wish to calculate the value of 5!. If n is 5, the for loop control expression
would be the row vector [1 2 3 4 5]. This loop will executed 5 times, with the variable ii
taking on values of 1, 2, 3, 4 and 5 in the successive loops. The resulting value of
n_factorial will be 1*2*3*4*5 = 120.

The break statement


There is a statement that can be used to control the operation of for loop: the break
statement. The break statement terminates the execution of a loop and passes control to
the next statement after the end of the loop. An example of the break statement in a for
loop is shown below.
for ii = 1:5
if ii == 3;
break;
end
fprintf(‘ii = %d\n’, ii);
end
disp([‘End of loop!’]);

When the program is executed, the output is:


ii = 1
ii = 2
End of loop!

Solving ODE Using ode45


ODE45 Solve non-stiff differential equations, medium order method. [T,Y] =
ODE45(ODEFUN,TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates the system of
differential equations y' = f(t,y) from time T0 to TFINAL with initial conditions Y0.
Function ODEFUN(T,Y) must return a column vector corresponding to f(t,y). Each row
in the solution array Y corresponds to a time returned in the column vector T. To obtain
solutions at specific times T0,T1,...,TFINAL (all increasing or all decreasing), use
TSPAN = [T0 T1 ... TFINAL]. An example of a nonstiff system is the system of
equations describing the motion of a rigid body

To simulate this system, create a function rigid containing the equations


function dy = rigid(t,y)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = -0.51 * y(1) * y(2);

Create another file called rigid.m with the following lines in it


[t,Y] = ode45(@rigid,[0 12],[0 1 1]);

Plotting the columns of the returned array Y versus T shows the solution
plot(T,Y(:,1),'-',T,Y(:,2),'-.',T,Y(:,3),'.')
Using Basic Plotting Functions

Creating a Plot
The plot function has different forms, depending on the input arguments. If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y versus the index of the
elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y
versus x.
For example, these statements use the colon operator to create a vector of x values
ranging from 0 to 2π, compute the sine of these values, and plot the result:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

Now label the axes and add a title. The characters \pi create the symbol π. See “text
strings” in the MATLAB Reference documentation for more symbols:
XLABEL('X = 0:2\PI ')
YLABEL('SINE OF X')
title('Plot of the Sine Function','FontSize',12)
Plotting Multiple Data Sets in One Graph
Multiple x-y pair arguments create multiple graphs with a single call to plot. For
example, these statements plot three related functions of x, with each curve in a separate
distinguishing color:
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)

The legend command provides an easy way to identify the individual plots:
legend('sin(x)','sin(x-.25)','sin(x-.5)')
Adding Plots to an Existing Graph
The MATLAB hold command enables you to add plots to an existing graph. When you
type
hold on

Now MATLAB does not replace the existing graph when you issue another plotting
command; it adds the new data to the current graph, rescaling the axes if necessary. For
example, these statements first create a contour plot of the peaks function, then
superimpose a pseudocolor plot of the same function:
[x,y,z] = peaks;
pcolor(x,y,z)
shading interp
hold on
contour(x,y,z,20,'k')
hold off

The hold on command combines the pcolor plot with the contour plot in one figure.

Setting Axis Limits


By default, MATLAB finds the maxima and minima of the data and chooses the axis
limits to span this range. The axis command enables you to specify your own limits:
axis([xmin xmax ymin ymax])

or for three-dimensional graphs,


axis([xmin xmax ymin ymax zmin zmax])

Use the command


axis auto

to enable automatic limit selection again.

Setting Grid Lines


The grid command toggles grid lines on and off. The statement
grid on

turns the grid lines on, and


grid off

turns them back off again.

Adding Axis Labels and Titles


The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command
adds a title at the top of the figure and the text function inserts text anywhere in the
figure. You can produce mathematical symbols using LaTeX notation in the text string,
as the following example illustrates:
t = -pi:pi/100:pi;
y = sin(t);
plot(t,y)
axis([-pi pi -1 1])
xlabel('-\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,-1/3,'{\itNote the odd symmetry.}')

Specifying Line Styles and Colors


It is possible to specify color, line styles, and markers (such as plus signs or circles) when
you plot your data using the plot command:
plot(x,y,'color_style_marker')

color_style_marker is a string containing from one to four characters (enclosed in single


quotation marks) constructed from a color, a line style, and a marker type. This example
plots the data twice using a different number of points for the dotted line and marker
plots:
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')

Save and Load


Save
save by itself stores all workspace variables in a binary format in the current directory in
a file named matlab.mat. Retrieve the data with load.
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

Load
load loads all the variables from the MAT-file matlab.mat, if it exists, and returns an error
if it doesn't exist.
load('filename') loads all the variables from filename given a full pathname or a
MATLABPATH relative partial pathname.
load('filename', 'X', 'Y', 'Z') loads just the specified variables from the MAT-file.
Roots of a polynomial

MATLAB has a built-in command that finds all the roots (real and complex) for any
polynomial. This command is roots:

r=roots(p);

The polynomial is defined by the vector of its coefficients, i.e. the roots of the polynomial
3 2 3 are found by:

p=[1 3 2 1 0 3];
r=roots(p)

r=

-2.4325
-0.8214 + 0.9767i
-0.8214 - 0.9767i
0.5376 + 0.6843i
0.5376 - 0.6843i

Inversely, knowing the roots, we can reassemble the polynomial. The command is poly.

p=poly(r)

p=

1.0000 3.0000 2.0000 1.0000 -0.0000 3.0000

Partial fraction expansion

The MATLAB command residue(r,p,k) returns the residues (coefficients) r of a partial


fraction expansion, the poles p and the direct terms k. There are no direct terms if the
highest power of the numerator is less than that of the denominator. If X(s) is a rational
function, i.e., then we can perform partial fraction expansion in Matlab as
follows:

1.

Ns = [3, 2];
Ds = [1, 3, 2];
[r, p, k] = residue(Ns, Ds)

r=
4
-1

p=
-2
-1

k=
[]

2.

Ns = [1, 3];
Ds = [1, 5, 12, 8];

[r, p, k] = residue(Ns, Ds)

r=

-0.2000 - 0.1500i
-0.2000 + 0.1500i
0.4000

p=

-2.0000 + 2.0000i
-2.0000 - 2.0000i
-1.0000

k=

[]

3.

Note we can multiply two polynomials using the command conv

Ns = [1 3]; % Coefficients of the numerator N(s)


d1 = [1 2 1]; % Coefficients of (s + 1)^2 = s^2 + 2*s + 1 term in D(s)
d2 = [0 1 2]; % Coefficients of (s + 2) term in D(s)
Ds=conv(d1,d2);% Multiplies polynomials d1 and d2 to express denominator D(s)
as polynomial

[r,p,k]=residue(Ns,Ds)

r=

1.0000
-1.0000
2.0000

p=

-2.0000
-1.0000
-1.0000

k=

[]

Linear Time Invariant Systems


Creating transfer function models

The function tf creates transfer functions. As before for rational functions, tf needs the
definition of two vectors, one containing the coefficients of the numerator polynomial -
taken in descending orders - and one for the denominator polynomial of the transfer
function.

s 3s 2
3 4 12
H=tf([1 3 2], [1 3 4 12])

Transfer function:

s^2 + 3 s + 2

----------------------

s^3 + 3 s^2 + 4 s + 12
We can obtain the pole-zero map of H(s) using the command pzmap:

pzmap(H)

The frequency response of the transfer function H(s) can be evaluated using the
command freqs as:

num=[1 3 2];

den=([1 3 4 12]);

freqs(num,den,1e-2:1e-2:100)
Note that we can also obtain the frequency response by replacing s with jω, i.e.:

j 3j 2
j
j 3 j 4j 12
and use the abs and angle commands to obtain the magnitude and phase of H(jω) (how?)

System interconnections

We can evaluate the transfer function of two systems connected in series or in parallel by
using the series and parallel commands respectively, e.g.:

1 3
,
2 4
Ha=tf(1,[1,2])

Transfer function:
1
-----
s+2

Hb=tf(3,[1,4])

Transfer function:
3
-----
s+4

Hser=series(Ha,Hb)

Transfer function:
3
-------------
s^2 + 6 s + 8

Hpar=parallel(Ha,Hb)

Transfer function:
4 s + 10
-------------
s^2 + 6 s + 8

Impulse and step responses


We can compute the impulse and step responses of an LTI system defined with the tf
command in Matlab by using the impulse and step commands, eg for Ha defined above
we have:

impulse(Ha)
step(Ha)

Verify the above results by computing the analytical expressions for the impulse and step
responses ha(t) and sa(t).
Bode diagrams

The magnitude and phase Bode diagrams for the frequency response of an LTI system
may be obtained using the bode command after defining the transfer function (using tf)
and the range of values for the frequency in logarithmic space using the logspace
command. Consider the system with the frequency response:

1
H ( jω ) = 2
⎛ ω ⎞ ω
⎜j ⎟ +j +1
⎝ ω0 ⎠ ω0
ω0 = 1rad / sec

The Bode diagrams can be obtained by the commands:

sys=tf([1], [1 1 1])

Transfer function:
1
-----------
s^2 + s + 1

w=logspace(-2,4);
bode(sys,w)
grid
Filtering

Analog lowpass, highpass, bandpass and bandstop Butterworth and Chebyshev filters can
be obtained using the butter and cheby1 commands as follows:

[B,A]=butter(N,ws,'low','s');

[B,A]=butter(N,ws,'high','s');

[B,A]=butter(N, [w1,w2], 'bandpass','s');

[B,A]=butter(5,1,'low','s');

where N is the filter order, ws is the cutoff frequency in rad/sec (lowpass or highpass
filters), [w1 w2] is the vector that specifies the passband and stopband for bandpass and
bandstop filters respectively and ‘s’ denotes analog filter.

For Chebyshev filters the syntax is the same replacing the command butter with cheby1.

The frequency response of a 5th order Butterworth filter with a cutoff frequency of ws=10
rad/sec can be plotted using:

[B,A]=butter(5,10,'low','s');

freqs(B,A)
The transfer function of this filter is:

sys=tf(B,A)

Transfer function:

1e005

------------------------------------------------------------

s^5 + 32.36 s^4 + 523.6 s^3 + 5236 s^2 + 3.236e004 s + 1e005

For Chebyshev filters a parameter that specifies the peak-to-peak ripple in decibels in the
passband needs to be specified also, i.e. for a ripple of 10dB we would have:

[B,A]=cheby1(N,R,ws,'low','s');

[B,A]=cheby1(5,10,10,'low','s');

freqs(B,A)

sys=tf(B,A)

Transfer function:

2083

-------------------------------------------------------

s^5 + 2.121 s^4 + 127.2 s^3 + 193.3 s^2 + 3251 s + 2083

You might also like