Professional Documents
Culture Documents
Getting Help: Example: Look For A Function To Take The Inverse of A Matrix. Try Commands "Help
Getting Help: Example: Look For A Function To Take The Inverse of A Matrix. Try Commands "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”.
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.
1 2
3 4
1 2 3 4
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
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
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
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
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
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.
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
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.
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.
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.
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=
-0.2000 - 0.1500i
-0.2000 + 0.1500i
0.4000
p=
-2.0000 + 2.0000i
-2.0000 - 2.0000i
-1.0000
k=
[]
3.
[r,p,k]=residue(Ns,Ds)
r=
1.0000
-1.0000
2.0000
p=
-2.0000
-1.0000
-1.0000
k=
[]
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(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
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(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
------------------------------------------------------------
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
-------------------------------------------------------