You are on page 1of 72

MATLAB FOR ENGINEERS

E.C. KULASEKERE
University of Moratuwa
Sri Lanka
Kluwer Academic Publishers
Boston/Dordrecht/London
Contents
v
List of Figures
vii
List of Tables
ix
Preface
E.C. KULASEKERE
xi
To all those who supported
Acknowledgments
To the different authors
xiii
Foreward
Forward text, to be written.
xv
Introduction
Test
xvii
Chapter 1
INTRODUCTION TO MATLAB
1. INTRODUCTION
The Matlab program is specially designed for matrix computations: solving
systems of linear equations, factoring matrices and so forth. It also has a built
in graphics package for visualization. Matlab is designed to solve problems
numerically, hence in most cases numerical values for the variables should
be dened prior to being used in a Matlab function. However, Matlab also
has limited support for non-numerical or symbolic computations. A subset of
commands given in Maple V symbolic math package made available to the
Matlab core.
Matlab command window is ready to accept command line function argu-
ments when the >> prompt is displayed. Any command issued at the command
prompt would be executed immediately and the result displayed. If the com-
mandis followedby; the result is not displayed. Matlabcomes withextensive
online help facility. The following commands can be issued to gain access to
this facility:
(1) help <function name> :- If the function name is known this command
returns a detail online help page for that function. For example, help plot
gives help on the plot command.
(2) doc :- Issuing this command at the Matlab command prompt will initialize
the html help database and open the web browser window.
(3) lookfor<regular expression>:- This command will initiate a sub-
string search of all the Matlab functions and return the results. Note that the
regular expression should be enclosed in single quotes if the expression has
more than one word.
1
2 MATLAB FOR ENGINEERS
2. MATRICES IN MATLAB
The basic data type in Matlab is and n-dimensional array of double preci-
sion numbers. For example a one dimensional array represents a vector (e.g.
[1 2 3]), a two dimensional array represents a matrix and multi-dimensional
arrays represents a multi-dimensional matrix. A scalar is a 1 1 matrix, a
n-dimensional vector is a n 1 matrix and so on.
Matrices are introduced into Matlab as a set of numbers enclosed in square
brackets (e.g. A=[1 2;3 4]) where the semi-colon ; marks the end of a row.
The matrix so entered will be displayed as shown below.
A =
1 2
3 4
Exercise 1 The transpose of a matrix is given by B = A.
Exercise 2 The size of a matrix can be found by issuing the command
size(A). What is the number of rows and columns in A?
An example of a complex number in Matlab is a = 1+2i. Amatrix of complex
numbers can be written as A=[1+2i 3+i; 1+4i 5+i6] and will be displayed
as,
A =
1+2i 3+i
1+4i 5+6i
Exercise 3 Find the real part and the imaginary part of the complex number
matrix given above. Hint: Use lookfor complex to nd the commands to
be use.
The variables inthe Matlabworkspace canbe viewedbyissuingthe command
who. These variable values can be cleared by issuing the command clear. A
specic variable can be cleared by issuing the command clear <variable
name>.
A regular Matlab expression is of the form variable=expression. The ex-
pression consists of other variables dened previously. If previously undened
variables are used you will see the error message
??? Undefined function or variable <missing variable>.
Variables in the expression should evaluate to numerical values or else they
should be dened as symbolic variables. Symbolic variables can be dened by
Introduction to Matlab 3
the sym <variable> command (see help on sym). Matlab variable names are
case sensitive. For example num is different from Num.
Matlab uses all the standard operators such as +, , and so on. All Matlab
operations are sensitive to the size of the matrix and will return an error message
if there are any incompatibilities. Remember that a mn matrix can only be
multiplied by a matrix of size n p. The same argument holds for addition,
subtractions and divisions of matrices. For example a 2 4 matrix cannot be
added to a matrix of size 2 3. The only instance where the matrix sizes are
not an issue is when scalar operations (matrix of size 1 1) are involved.
Individual matrix and vector entries can be referenced with indices enclosed
in parentheses. The general form of the notation is A(row,column). For
example, A(2,1)=1+4i for the complex matrix given above. Note that the
index into a Matlab matrix cannot be zero or negative.
The colon symbol (:) is one of the most important operators in Matlab. It
can be used to,
(i) create vectors and matrices, eg. a = 1:6,
(ii) specify sub-matrices or vectors, eg. A(1:2,3:4) is a sub-matrix,
(iii) perform iterations, eg. for i = 1:4.
These will be discussed in detail later in this section. The period (.) converts
an operator into an element wise operation. For example [1 2;3 4]*[1 2;3
4]=[7 10;15 22]however [1 2;3 4].*[1 2;3 4]=[1 4;9 16]. The pe-
riod operation has multiplied [1*1 2*2;3*3 4*4] rather than treating it as a
matrix multiplication. The same procedure applies to all other operators as
well.
The colon operator can also be used to extract sub-matrices in the follow-
ing manner. A(1:2,1)=[1+2i 1+4i]. The general form of a sub-matrix
notation is
A(start_row_index:end_row_index,start_col_index:end_col_index)
Some special matrices that Matlab can generate are shown below.
ones(rows,columns) produces a matrix with all the elements being unity.
eye(n) produces a n-dimensional identity matrix.
zeros(rows,columns) produces a matrix with all the elements being zero.
Exercise 4 Find the square of the center 3-by-3 matrix from a 5-by-5 matrix
of your choice.
4 MATLAB FOR ENGINEERS
3. PROGRAMMING IN MATLAB
A Matlab expression entered at the command line will get processed imme-
diately and the resulting output will be displayed. However, for complex or
longer sequences of program code we can use a Matlab script le. This is a
text le with the extension .m. A further improvement to this can be obtained
by writing the script with input output capabilities. Note that the newly created
m-les should be in your path.
function [output variables] = function_name(input variables)
% help text for the function
% The percentage sign indicates the beginning of a
% comment or remark.
% ....
% .....
% End of help information
....
....
variables and expressions
...
..
The outputs and inputs are a set of comma separated variable values which
can be used to reference the computations within the function. The function
le should be saved in a le with the same name as the function name and
with extension .m. Matlab offers all the standard constructs, such as loops and
conditionals that are available in other programming languages.
% The IF statement
if expression1
statements containing previously defined Matlab variables
elseif <a logical or conditional expression>
statements containing previously defined Matlab variables
....
else
statements containing previously defined Matlab variables
end
% FOR loop
for n = Start:Step:End
statements containing previously defined Matlab variables
...
end
Introduction to Matlab 5
% WHILE loop
while <logical or conditional loop terminating criteria>
statements containing previously defined Matlab variables
...
end
Nestedconditionals are also allowed. The conditional or logical expressions use
relational (or logical) operators such as <, >, <=, >=, == (logical equal), =
(logical not-equal) in its construction. These are binary operators that return
values 0 (False) or 1 (True) for scalar arguments.
Exercise 5 Given two integers a and b, write a sequence of statements in
a Matlab script le to display T if a b and display F otherwise using the
IF-ELSE construct.
Exercise 6 Use the FOR-loop construct to nd the sum of integers from 1 to
10. Redo the exercise using the WHILE-loop construct.
Matlab also provides scalar functions like sin, cos, tan, asin, acos,
atan, exp, log, abs, sqrt and round. Some of the vector functions
available in Matlab are max, min, sort, sum, prod, any and all.
Example 1 Write a simple Matlab function to compare two matrices a and
b and return the matrix that has the smallest element.
To obtain the smallest element in a matrix we can use the Matlab min function.
Note that the problem does not state the matrix size. Hence the program has to
be written to accommodate unequal matrix sizes. The following code segment
should be saved in a Matlab le named compare.m.
function [s] = compare(a,b)
% Help for compare
% [s] = compare(a,b)
% s - Output variable
% a,b, input numbers
if (min(min(a)) < min(min(b)))
s = a;
else
s = b;
end
Exercise 7 Write a Matlab function to accept two vectors and return the
multiplication of the average values of the two vectors.
6 MATLAB FOR ENGINEERS
4. MATLAB PLOTTING COMMANDS
Matlab creates xy- polar- semilog- discrete- and bar graphs. The simplest
form of a graph is created using the plot command. Use the Matlab help
facilitytoget more information onthe plotting commands. Some of the graphics
commands that will be used in this report are listed below.
Two dimensional graphs.
Elementary X-Y graphs.
plot - Linear plot.
loglog - Log-log scale plot.
semilogx - Semi-log scale plot.
semilogy - Semi-log scale plot.
plotyy - Graphs with y tick labels on the left and right.
Axis control.
axis - Control axis scaling and appearance.
grid - Grid lines.
hold - Hold current graph.
axes - Create axes in arbitrary positions.
subplot - Create axes in tiled positions.
Graph annotation.
title - Graph title.
xlabel - X-axis label.
ylabel - Y-axis label.
text - Text annotation.
gtext - Place text with mouse.
To plot a single set of data y vs t the command plot(x,y) can be used. Here
both y and x should have the same size. To plot multiple variables on the same
plot we can use the command plot(x1,y1,x2,y2,...,xn,yn). One plot
can be held on the graph window by issuing the command hold. Matlab has
predened line colors and lines types that can be used to differentiate different
plots. A subset of the possible values are given below.
Line Types Indicators Point Types Indicators Color Symbol
Solid - Point . Red r
Dash -- Plus + Green g
Dotted : Star * Blue b
Dashdot -. Circle o Cyan c
For example plot(x,y,:) would plot the graph with a dotted line. A new
gure window can be opened by issuing the command figure(<number>).
Introduction to Matlab 7
Text can be placed at any position on the plot using the gtext command.
For example gtext(place) would produce a cross-hair on the plot window
which can be used to place the text. Conversely you can use the ginput
command to transfer x-y value pairs from the plot window to the Matlab work
space. For example x=ginput(2) command will extract two points from the
plot and assign them to x.
Matlab selects axis limits based on the range of the plotted data. You can
also specify the limits manually using the axis command. Call axis with the
new limits dened as a four-element vector,
axis([xmin, xmax, ymin, ymax])
Note that the minimum value should be less that the maximum value.
Exercise 8 Plot one cycle (2) of a sine wave. Add axis labels and a title
and print.
5. OTHER RELEVANT COMMANDS
break This command may be used to terminate the execution of FOR and
WHILE loops. If the break command exists in the inner most part of a
nested loop, a break statement inside the inner loop will exit from that loop
only. The break command is useful in exiting a loop when an error condition
is detected.
disp This command displays a matrix or string without printing its name. For
example disp(x) will display the contents of the matrix without the ans=
comment.
formatcontrols the format of the Matlaboutput. For example format short
will round all Matlab numerical outputs to 5 signicant decimal digits.
pi represents the variable .
diary saves a session into a disk, possibly for printing or inclusion of a
report at a later time. diary on will activate saving all the key strokes in
a le called diary in the current directory and the command diary off
terminated the writing process. Use any text editor to edit the contents in
diary.
Ctrl-C key sequence will terminate the execution of the current program. This
can be used as the emergency stop for unwanted operations.
Exercise 9 The output voltage of a rst order transient circuit is given by
v
o
(t) = 2 3.2e
3t
V
8 MATLAB FOR ENGINEERS
Plot the response using Matlab for t 0.
Exercise 10 The equivalent impedance of a circuit
1
is given by
Z
eq
(j) = 100 +jL +
1
jC
If L = 4H and C = 1F,
Plot |Z
eq
(j)| vs. .
What is the minimum impedance?
What is the corresponding frequency at this minimum impedance?
1
Electronics and Circuit Analysis using Matlab by J. Attia
Chapter 2
SIGNAL PROCESSING USING MATLAB
1. DC ANALYSIS OF ELECTRIC CIRCUITS
In this section we will discuss DC analysis of an electric circuit via Matlab
matrix manipulations. The nodal voltages or the loop currents can be used to
obtain a set of linearly independent circuit equations which then can be solved
using matrix manipulations in Matlab.
Example 2 For the circuit shown in Fig. 2.1, obtain the voltage drop V
o
across the 4k resistor.

+
6V
2k
4k
4k
+
V
o

8k
8k
2mA
v
1
v
2
Figure 2.1.
The nodal equations for the above system can be written as,
v
1
6
2
+
v
1
4
+
v
1
v
2
4
= 0 (2.1)
v
1
v
2
4
+
v
2
8
2 = 0 (2.2)
These equations can be converted into [Y ][V ] = [I] format where V is a column
vector [v
1
v
2
]
T
. The following Matlab code segment can be used to compute
numerical values for the column vector.
9
10 MATLAB FOR ENGINEERS
% This is the matlab code to solve for the nodal voltages.
Y = [ 1 -1/4;
-1/4 3/8];
I=[3 2];
V = inv(Y)
*
I;
Vo = V(1)-V(2)
% This could also be computed by defining one variable as
shown below.
V = inv([1 -1/4;-1/4 3/8])
*
[3 2];
The method of analysis will not change even if their are dependent sources in the
circuit. The circuit equations can be written by treating the dependent sources
as independent sources and later substituting the control parameter. Then the
nal set of equations can be formulated as a multiplication of matrices in the
general form[A][B] = [C] which could then be solved using Matlab. The same
procedure is applied to Mesh analysis as well. However in this case the matrix
equation will be of the form [R][I] = [V ] where [R] is the impedance matrix.
To nd the Thevenin equivalent circuit one has to write the circuit equations
as usual and then use Matlab to solve for the unknown variables. If the circuit
contains only dependent sources then a test voltage of 1V (or 1A current source
as the case maybe) should be applied across the terminals where the Thevenin
resistance is computed. If the circuit contains both dependent and independent
sources one can use the identity R
th
= v
oc
/i
sc
to compute the equivalent
resistance.
Example 3 Determine R
th
at the terminals AB for the network shown in
Fig. 2.2.

+
2000I
x
2k
1k
I
x
3k
2k 1mA
A
B
V
1
V
2
Figure 2.2.
Since there are only dependent sources we apply a 1mA current source across
the terminals A-B. If the terminal voltage V
2
is computed, R
th
= V
2
/1E 3
will provide the Thevenin resistance. The nodal equations for the circuit are
Signal Processing Using Matlab 11
given by,
V
1
2000I
x
2k
+
V
1
1k
+
V
1
V
2
3k
= 0
V
2
V
1
3k
+
V
2
2k
= 1E 3
I
x
=
V
1
1k
The following code will compute R
th
.
Y = [4/3 -1/3;-1/3 5/6];
I = [0 1E-3];
% Since the resistors are considered t be in kOhms V is in mV
V = inv(Y)
*
I;
Rth = V(2)/1E-3;
% The answer is 1.3kOhms
In the above examples Matlab matrix manipulations are used to compute
unknown circuit variables. In the next example we will see how Matlab can be
used in a design situation to obtain circuit parameters.
Example 4 (Maximum Power Transfer Theorem) A10VDCpower
source has an internal resistance of 100. Design the load resistor R
L
such
that maximum power is transferred.
The following code segments achieves this task.
function [R] = maxpower(RL)
% function [R] = maxpower(RL)
% R : Resistance at which Max. power is transferred.
% RL: The vactor containing the RL values.
VS = 10;
RS = 100;
P = (VS^2
*
RL)./(RS+RL).^2;
plot(RL,P)
R = max(P);
The peak in the graph corresponds to the maximum power and the associated
resistor can be chosen as R
L
.
2. TRANSIENT ANALYSIS
In this chapter we perform what is known as transient analysis of rst and
second order circuits via Matlab functions. The circuits we consider will have
12 MATLAB FOR ENGINEERS
one or two storage element which can be represented by a rst or second or-
der differential equation respectively. Our analysis will involve nding circuit
equations and plotting the time domain response of a circuit after a sudden
change in the network due to switches opening or closing. There are several
methods available for transient analysis via Matlab.
(1) If the equation of the transient is known, Matlab can be used to plot the
waveform. In order to do this a time vector can be dened using [Start:
Step: Stop] and use matrix manipulations on the equation to nd the
values of the function at these time instances.
(2) If the equation is not known but the differential form is known together with
a set of initial conditions, Matlab can be used to obtain the time response
using the ode23 function.
(3) If the differential form is not known, replace the circuit elements with their
Laplace equivalents and obtain the transfer function at the output variable
of interest. This can then be used together with the impulse function in
Matlab to arrive at the output response.
(4) If the input waveform type is known (for example a step input) we can
obtain the transfer function from the input to the output which can then be
simulated via the lsim function in Matlab.
We will investigate the application of some of the methods available for transient
analysis using several examples in the sections that follow.
2.1. DIFFERENTIAL EQUATION REPRESENTATION
OF CIRCUITS
Ordinary differential equations (ODE) often involve a number of dependent
variables, as well as derivatives of order higher thanone. Touse the MatlabODE
solvers, you must rewrite such equations as an equivalent system of rst-order
differential equations. i.e. an equation of the form
dx(t)
dt
= f(t, x).
Any ODE can be written in the form
d
n
x(t)
dt
n
= f(t, x,
dx(t)
dt
, . . . ,
d
n1
x(t)
dt
n1
).
Then the above equation can be written as a system of rst order equations by
making the substitutions
x
1
= x, x
2
=
dx
dt
, . . . , x
n
=
d
n1
x
dt
n1
.
Signal Processing Using Matlab 13
The result is an equivalent system of n rst order ODEs of the form
dx
1
dt
= x
2
dx
2
dt
= x
3
.
.
.
dx
n
dt
= f(t, x
1
, x
2
, . . . , x
n
)
Once you represent the equation as a system of rst order ODEs, you can code
it as a function that the MATLAB ODE solver can use. The function should be
of the form dxdt = odefunction(t,x). The following example illustrates
this procedure.
A rst-order transient circuit with one storage element can be represented
by a rst order differential equation of the form.
dx(t)
dt
+ax(t) = f(t)
The solution to such a equation is provided by the Matlab function ode23. The
differential denition function for this case is
function [dx] = odefunc(t,x)
% help instructions if necessary
dx = f(t)-ax;
Then one has to choose the initial conditions and the stop time for the sim-
ulation (for more information issue help ode23 at the command prompt) as
x=0 and time = [0 2]. The solver is called using the statement [t, vo] =
ode23(odefunc,[0 2],0); where vo is the output state.
This procedure can be extended to the second order transients as well. Con-
sider the second order ODE given by
d
2
x(t)
dt
2
+a
1
dx(t)
dt
+a
2
x(t) = f(t)
We choose variables x
1
and x
2
such that (note that these are function in time)
x
1
= x and
dx
1
dt
= x
2
Then
dx
2
dt
= ax
2
bx
1
+f(t)
14 MATLAB FOR ENGINEERS
If we assume y = [x
1
(t) x
2
(t)]
T
, we can write the Matlab differential denition
le used by ode23 as
function dy = diff1(t,y)
dy = zeros(2,1); % To ensure that dy is a column vector
dy(1) = y(2);
dy(2) = -a
*
y(2)-b
*
y(1)+f(t)
% Here f(t) has to be defined or should be deterministic.
Once calls the ODE solver ode32 in the same manner as in the rst order
ODE case. However in this case the initial conditions will have two values.
The values of dy that is returned from the differential denition should be a
column vector. Hence we use the zeros function in Matlab to ensure its correct
dimensions.
2.2. LAPLACE TRANSFORMMETHODS FOR
TRANSIENT ANALYSIS
The response of a system to initial conditions can also be found using the
Laplace transformrepresentation of the circuit. In some cases this is also known
as the network function of the circuit. For example if the input output equation
is represented by
a
n
d
n
y
dt
n
+a
n1
d
n1
y
dt
n1
+. . . +a
0
y = b
m
d
m
y
dt
m
+b
m1
d
m1
y
dt
m1
+. . . +b
0
y,
where x(t) is the input and y(t) is the output, the network function can be
represented by
H(s) =
Y (s)
X(s)
=
b
m
s
m
+b
m1
s
m1
+ +b
0
a
n
s
n
+a
n1
s
n1
+ +a
0
.
The above expression can be entered into Matlab as a numerator and denomi-
nator polynomials given by
num = [a
n
a
n1
. . . a
0
] and den = [b
m
b
m1
. . . b
0
].
Note that the coefcients should be arranged in descending powers of s. The
procedure for simulating the transient response using the Laplace method is as
follows. The initial conditions are found after the circuit state changes when
the switch is closed. Then replace the circuit elements with their corresponding
Laplace equivalents and then obtain the transfer function as a rational polyno-
mial as shown above. One can use the function lsim in Matlab to simulate
the transient response. In what follows we provide several examples which
illustrate these modeling procedures.
Signal Processing Using Matlab 15
2.3. TRANSIENT ANALYSIS EXAMPLES
The simplest form of analyzing a transient circuit is to dene a time vector
via [Start: Step: Stop] and then compute the values of the transient
time domain equation explicitly via matrix manipulations.
Example 5 Assuming V
s
= 10V DC source, C = 1F and R = 100k,
use Matlab to plot the transient voltage across the capacitor.

+
V
s
R
C

V
o
(t)
+
Figure 2.3.
In the absence of additional information we can assume that the capacitor is
initially unchanged. Then the output voltage V
o
(t) changes according to,
V
o
(t) = V
s
(1 e

1
RC
t
)
Direct Method
One can directly simulate the nal equation for V
o
(t) using the following code
segment.
C = 1e-6;
R = 100e3;
Vs = 10;
% Then the time constant in ms is
tau = R
*
C;
% The plot for 1 s with 0.02s intervals
t = 0:0.02:1;
Vo = Vs
*
(1-exp(-t/tau));
plot(t,Vo)
grid
title(Charging of a Capacitor)
xlabel(Time (s))
ylabel(Vo(t) (Volts))
The plot that is obtained from the above code segment is given in Figure 2.4.
ODE Method
16 MATLAB FOR ENGINEERS
0 0.2 0.4 0.6 0.8 1
0
1
2
3
4
5
6
7
8
9
10
Charging of a Capacitor
Time (s)
V
o
(
t
)

(
V
o
l
t
s
)
Figure 2.4. Vo(t) - across the capacitor
The ODE governing the circuit in Figure 2.3 is
dv
C
dt
+
v
C
RC
=
V
S
RC
The following code segment can be used to simulate the ODE. The following
code is saved in a separate le named diff1.m.
function [dy] = diff1(t,y)
% Help statement is necessary
R = 100e3; C = 1e-6; Vs = 10;
dy = Vs/(R
*
C)-y/(R
*
C);
Now the ODE solver can be used to simulate the output state via the following
code segment.
[t,y] = ode23(diff1,[0 1], [0]);
plot(t,y)
grid;
title(Charging of a Capacitor)
xlabel(Time (s))
ylabel(Vo(t) (Volts))
Again we have assumed the initial condition associated with the state is zero.
We obtain Figure 2.4 again.
Signal Processing Using Matlab 17
Laplace Method
The circuit in Figure ?? can also be simulated via a Laplace transformed circuit.
The DCvoltage source is replaced with a step function and the circuit is replaced
by its corresponding transfer function. The transfer function is given by,
V
o
(s)
V
s
(s)
=
1
1 +RCs
.
However if we take V
s
(s) = 10/s the system output is then given by the
impulse response of the circuit. The following matlab code segment can be
used to obtain the output state.
% Simulating the Laplace transformed circuit.
R = 100e3;
C = 1e-6;
num=[10];
den=[R
*
C 1 0];
sys = tf(num,den);
% The following command will simulate a step
impulse(sys)
Another way of simulating the system is to assume the input signal form and
use the lsim function in Matlab to explicitly compute the output state. For
example V
s
(s) corresponds to a step function with amplitude 10V. Then,
% Simulating using an explicit input
%R = 100e3; C = 1e-6;
num = [1]; den = [RC 1];
sys = tf(num,den);
U = 10
*
ones(1,100); % this simulates the step input.
T = 0:1/size(U,2):1-1/size(U,2); % This is the corresponding time signal
% Make sure that the U and T vectors match in length
lsim(sys,U,T); % will simulate the output state.
Example 6 For the transient circuit shown in Fig. 2.5, the initial current
owing through the inductor is zero. At t = 0 the switch is moved from a to
b, where it remains for 1 second. After which it is moved from b to c where it
remains indenitely. Plot the current ow through the inductor with respect to
time.
Direct Method
For the time duration 0 < t < 1 sec, the equations that governs the current
through the inductor is given by,
i(t) = 0.4(1 e

1
), where
1
=
200
50 + 50
= 2s. (2.3)
18 MATLAB FOR ENGINEERS

+
40V
50
150
200H
50
t = 0
a b
c
Figure 2.5.
At t = 1 the current in the circuit will act as the initial value I
0
for t > 1.
i(t = 1) = 0.4(1 e
0.5
) = I
0
The circuit equation that governs the transient at t > 1 is given by,
i(t) = I
0
e

t1

2
, where
2
=
200
150 + 50
= 1s. (2.4)
The matlab code to plot the transient is given below.
% Code to simulate the transient of above example
t1 = 0:0.01:1; tau1 = 2;
i1 = 0.4
*
(1-exp(-t1/tau1));
n = size(t1);
I0 = i1(n(2));
t2 = 1:0.01:6; tau2 = 1;
i2 = I0
*
exp(-(t2-1)/tau2);
plot(t1,i1); hold
plot(t2,i2)
grid
title(RL Transient circuit)
xlabel(Time Sec)
ylabel(Inductor Current (A))
The gure for the above code is given in Figure 2.6.
Laplace Method
The above problem can also be solved using the Laplace equivalent circuits
shown in Figure 2.6 From the Laplace equivalent circuit for 0 t < 1 the
current is
I(s) =
0.2
s
2
+ 0.5s
We can explicitly simulate this equation using the impulse function. The
t = 1 value of the current will act as the initial condition I
0
for the Laplace
Signal Processing Using Matlab 19
0 1 2 3 4 5 6
0
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
RL Transient circuit
Time Sec
I
n
d
u
c
t
o
r

C
u
r
r
e
n
t

(
A
)
Figure 2.6. RL Transient

+ 40
s
50 200s
50
(a) Circuit for 0 t < 0
150
200s
+
sI
0
50
(b) Circuit for t 0
circuit for t 1. The equation for the current will now be governed by
I(s) =
sI
0
200s + 200
The Matlab code to simulate this system is shown below.
20 MATLAB FOR ENGINEERS
% The simulation for system sys1 for 0<= t < 1
sys1 = tf([0.2],[1 0.5 0]);
[Y1,T1] = impulse(sys1,1);
% I0 is the last value in Y1.
I0 = Y1(size(Y1,1));
% The simulation for system sys2 for t>= 1
sys2 = tf([I0 0],[200 200]);
[Y2,T2] = impulse(sys2,[1:0.1:6]);
plot(T1,Y1,T2,Y2)
Example 7 Plot v
o
(t) for t > 0 in the circuit given below including the time
interval just prior to opening the switch.

+
12V 6k
6k
6k
100F
.t = 0

v
o
(t)
+
Figure 2.7.
Direct Method
For the interval just prior to opening the switch, the capacitor is an open circuit
and v
o
(t = 0

) = 12 6/(6 + 6). The capacitor initial value is 6V . However


when the switch opens, the output voltage drops to v
o
(t = 0
+
) = 6 6/(6 +
6) = 3V . The capacitor will discharge through an equivalent resistance of
4k. The output for t > 0 is given by,
v
o
(t) = 3e

t
0.4
% for the time just prior to the opening of the switch
t1=-0.5:0.1:0
v1 = 6
*
ones(1,6);
% for t > 0
t2 = 0:0.01:2;
Signal Processing Using Matlab 21
v2 = -3
*
exp(-t2/0.4);
plot(t1,v1,t2,v2)
axis([-1 2 -4 7]) % Will center the plot on the window
The Matlab plot obtained from the code is given in Fig. 2.8.
1 0.5 0 0.5 1 1.5 2
4
3
2
1
0
1
2
3
4
5
6
7
Time (s)
v
o
(
t
)

(
V
)
Figure 2.8. The output transient voltage
ODE Method
The differential equation that governs the circuit behavior for t > 0 is given by,
dv
o
dt
=
5
2
v
o
(2.5)
The above equation has an initial condition given by, v
o
(t = 0
+
) = 3V. The
following matlab code can be used to generate the transient response at the
output. The differential denition is given by,
% The differential function used in the code has to be saved
% in a separate file called diff1.m
function dy = diff1(t,y)
dy = -(5/2)
*
y;
Then the output state can be computed by the Matlab ODE solver
%issue the commands at the commmand prompt
[t,v0] = ode23(diff1,[0 2],-3);
plot(t,v0)
22 MATLAB FOR ENGINEERS
The plot of the output signal for the time interval just before the switch is closed
will be the same as given in the previous case.
Example 8 Find the transient output v
o
(t) for t > 0 i the circuit given below.

+
12e
4t
V
1
t = 0
500mH
2

v
o
(t)
+
Figure 2.9.
In this example it can be seen that the input signal is not a DC source with a
xed value input. However the analysis methods available can still be used to
nd the transient output. The time domain equation for the output is
v
o
(t) = 24(e
6t
e
4t
). (2.6)
The differential equation that governs the output voltage is found to be,
dv
o
dt
+ 6v
o
= 48e
4t
(2.7)
The Laplace representation of the output voltage is given by,
V
o
(s) =
48
s
2
+ 10s + 24
. (2.8)
The code below shows how to solve for the output using the three different
methods we have leant so far. The Fig. 2.10 shows the output plot from the
simulations.
% Using direct computation.
t = 0:0.01:2;
vo = 24
*
(exp(-6
*
t)-exp(-4
*
t));
plot(t,vo)
The differential denition is given by
function dy = diff1(t,y)
dy = -6
*
y-48
*
exp(-4
*
t);
end
Signal Processing Using Matlab 23
The differential solver for the above is
[T,Y] = ode23(diff1,[0 2],0);
plot(T,Y)
% The Laplace equivalent simulatin
sys = tf([-48],[1 10 24]);
impulse(sys)
The simulations result in an output voltage shown in Figure 2.10.
Time (sec)
A
m
p
l
i
t
u
d
e
0 0.5 1 1.5
4
3.5
3
2.5
2
1.5
1
0.5
0
Figure 2.10.
Example 9 Find the transient response across the 3 resistor.
Direct Method
The time domain equation for v
o
(t) is given by,
v
o
(t) = 13.5e
2t
9e
4t
. (2.9)
Since the expression for the v
o
(t) is known we can simply simulate the transient
waveform for a dened time period.
% Choose a time span to simulate the output.
t = 0:0.01:2;
v = 13.5
*
exp(-2
*
t)-9
*
exp(-4
*
t);
plot(t,v)
xlabel(time (sec))
24 MATLAB FOR ENGINEERS

+
12V
t = 0
8
1
2
H

v
o
+
3
1
4
F

+
6V
t = 0
Figure 2.11.
ylabel(v_o(t) (V))
title(Transient output across 3\Omega)
The output from the above code is given in Fig. ??.
0 0.5 1 1.5 2
0
1
2
3
4
5
6
time (sec)
v
o
(
t
)

(
V
)
Transient output across 3
Figure 2.12.
ODE Method
Signal Processing Using Matlab 25
If the current in the circuit is i(t) after the switch is closed the ODEthat governs
the circuit response is given by
d
2
i
dt
2
+ 6
di
dt
+ 8i = 0, with i(t = 0
+
) = 1.5 and v
C
(t = 0
+
) = 0. (2.10)
We use x
1
= i and x
2
= di/dt to convert (??) into two rst order ODEs
x
1
= x
2
x
2
= 8x
1
6x
2
The differential code segment for the above ODE is
function dx = diff1(t,x)
dx = zeros(2,1); % This will ensure that dx is a column vector
dx(1) = x(2);
dx(2) = -8
*
x(1)-6
*
x(2);
The two initial conditions are x
1
(t = 0
+
) = i((t = 0
+
) and x
2
(t = 0
+
) =
di
dt
|
t=0
+. TOndthe initial condition for x
2
we turnbacktothe original equation
v
L
+v
R
+v
C
= 6
Substituting the initial conditions we nd
di
dt

t=0
+
=
6 v
C
(t = 0
+
) Ri(t = 0
+
)
L
= 3.
The differential solver for a 2 sec. time duration given by
[t,y] = ode23(diff1,[0 2], [1.5 3]);
% The voltage drop across the 3Ohm resistor is given by
plot(t,3
*
y(:,1))
2.4. DESIGN EXAMPLES
Example 10 A simple RLC circuit can be used to model an automobile ig-
nition system
1
. Consider the RLC circuit given in Figure ??. The inductor is
the ignition coil which is magnetically coupled to the starter (the starter is not
shown in the gure). The internal resistance of the inductor coil (L = 200 mH)
is denoted by R and is given to be 4 . Initially the battery e(t) = 12V is
connected to the series RLC circuit. To start the motor the battery is removed
via the switch at t = 0, thereby discharging the capacitor through the inductor.
26 MATLAB FOR ENGINEERS

+
e(t)
L R
C
i(t)
Switch
Figure 2.13. A simple RLC circuit
The starter operation requires that the current through the inductor to be
over damped. Do the following.
(1) Show that the RLC circuit in Figure ?? can be characterized by two rst
order differential equations. Also show that these two differential equations
can be reduced to an integrator-differential equation of the form,
dy(t)
dt
+ay(t) +b
_
t
0
y()d = x(t)
Also show that this equation can be reduced to a second order differential
equation.
(2) Find The systems characteristic equation and determine the roots in terms
of R, L and C.
(3) When the switch is turned on at t = 0 design for the value of the capacitor
C such that the current i(t) reaches 1 A within 100 ms after switching and
remains above 1 A for a time between 1 and 1.5 s. Obtain the design values
manually and also via Matlab using the following methods.
(4) Verify using Matlab that the system is over damped by nding the damping
ratio and the natural frequency. (Hint : use roots or damp)
We have to take into account the physical status of the starter motor operation
and howit effects our analysis. Before the switch is closed the capacitor charges
up with a current in the clockwise direction in the circuit. However when the
switch is ipped the current in the circuit is reversed when it discharges through
the starter coil. We need to account for this sign change in some manner. This
will be discussed as the we proceed. First we note that the equation of the
circuit after the switch is closed is
v
c
+v
L
+v
R
= 0 (2.11)
1
Basic Engineering Circuit Analysis: J. David Irwin and Chwan-Hwa Wu.
Signal Processing Using Matlab 27
We have assumed that the capacitor voltage is taking its direction from the
circuit after the switch is closed so we can conveniently assume that the initial
voltage for the capacitor is v
C
(t = 0
+
) = 12 rather than the positive value
before the switch is closed.
We use (??) to obtain the following:
v
c
+L
di
dt
+iR = 0 (2.12)
di
dt
= i
R
L

v
C
L
, (2.13)
and we also note that,
dv
C
dt
=
i
C
. (2.14)
These two rst order differential equations will characterize the circuit in Fig-
ure. ??. If we substitute for v
C
from (??) in (??) we get the integro-differential
equation
L
di
dt
+
1
C
_
idt +iR = 0 (2.15)
Differentiating (??) and getting the Laplace transform we get the following
characteristic equation.
s
2
+
R
L
s +
1
LC
= 0 (2.16)
Since it is given that the system is over-damped we should have two real and
unequal roots. Lets call them s
1
and s
2
. Then we have the following.
(s +s
1
)(s +s
2
) = s
2
+ (s
1
+s
2
)s +s
1
s
2
= s
2
+
R
L
s +
1
LC
From which we can deduce that;
s
1
+s
2
=
R
L
= 20
s
1
s
2
=
1
LC
We now have to choose arbitrary values for s
1
and s
2
and draw the current
waveform to see if the design specications are satised. For example if we
use the differential equation method to draw the current waveform we have to
use the equations (??) and (??) to write the differential equation denition in
matlab as follows. let y [v
c
, i
L
] be our state vector.
function dy = diff1(t,y)
dy = zeros(2,1) % This statement makes sure a vector is returned for dy
28 MATLAB FOR ENGINEERS
dy(1) = y(2)/C;
dy(2) = -y(1)/L-y(2)
*
R/L;
Save the above statements in diff1.m. Substitute the appropriate values for R,
L and C as the case may be. The the function is called by issuing the command
[T,Y] = ode23(diff1,[0 2],[-12 0]);.
Example 11 For the circuit given in Figure ??, choose the value of C for
critical damping.

+
V
s
(t)
C
6H 1F 1

v
o
(t)
+
Figure 2.14.
Before we proceed any further we note the following:
Over-damped system: > 1 and s =
0

0
_

2
1.
Under-damped system: < 1 and s =
0
j
0
_
1
2
.
Critically damped system: = 1 and s =
0
,
0
.
The Laplace equivalent circuit is used to nd the network function of the circuit
or also known as the transfer function of the system.
V
o
(s)
V
S
(s)
=
6Cs
2
(6C + 6)s
2
+ 6s + 1
. (2.17)
The roots of the denominator polynomial will determine the damping of the
system. Hence we carry out the design by changing the values of the capacitor
C until the system system damping ration = 1. We use the following Matlab
program for this purpose.
function [p,z] = sysfind(Cl,Ch,step)
C = [Cl:step:Ch];
figure(1);hold;
figure(2);hold;
for i = 1:size(C,2)
sys = tf([6
*
C(i) 0 0],[6
*
(C(i)+1) 6 1]);
Signal Processing Using Matlab 29
[wn,z,p] = damp(sys);
figure(1)
plot(real(p),imag(p),x)
% The text statement will enable us to identify the
% correct point on the output graphs.
text(real(p),imag(p),num2str(C(i)))
figure(2)
plot(i,z,+)
text(i,z(1),num2str(C(i)))
end
We plot the roots of the characteristic equation and the damping factor for
Cl=0.1, Ch = 0.9 and step = 0.1. The corresponding output graphs are
given in Figure ??.
It can be seen that the Critically damped poles occur at s = 0.33, 0.33
and the corresponding capacitor value is C = 0.5F.
We now proceed to do the same computation manually in order to illustrate
the procedure. The characteristic polynomial for the givensystemcanbe written
as
s
2
+ 2
0
s +
2
0
s
2
+
1
C + 1
s +
1
6C + 6
.
From which we deduce

0
=
_
1
6C + 6
and =
_
3
2C + 2
.
For critical damping = 1 which implies C = 0.5F.
In this section we concentrate on the AC behavior of circuits in two stages.
First is when the circuit is driven by a sinusoidal signal source of constant
frequency and secondly when the circuit is driven by a variable frequency
source. For these analysis types we ignore the effect of initial conditions,
transients or natural responses which will eventually vanish at the steady state.
3. AC STEADY STATE ANALYSIS
In this section we discuss the steady-state forced response of networks with
sinusoidal driving functions. In Matlab the angles are assumed to be in radians
unless otherwise mentioned. For example if we wish to plot the waveformgiven
by v(t) = 10 cos(t + 45
0
) we will use the following code.
wt = 0:0.01:2
*
pi;
v = 10
*
cos(wt+45
*
pi/180);
plot(wt,v)
% the degrees to radians conversion can also be done using a
30 MATLAB FOR ENGINEERS
0.7 0.6 0.5 0.4 0.3 0.2
0.15
0.1
0.05
0
0.05
0.1
0.15
0.1 0.1 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5
0.6
0.6
0.7
0.7
0.8
0.8
0.9
0.9
Real
I
m
a
g
i
n
a
r
y
(a) Poles of the System
1 2 3 4 5 6 7 8 9
0.85
0.9
0.95
1
1.05
1.1
0.1 0.2 0.3 0.4 0.5
0.6
0.7
0.8
0.9

(b) Damping Ration of the System


Figure 2.15.
% Matlab function.
v = 10
*
cos(wt+deg2rad(45));
Signal Processing Using Matlab 31
In steady state analysis, the circuit components are replaced by complex num-
bers. For example, the inductor of value L is represented by jL where is
the frequency of operation. The real part and the complex part of a complex
number can be found using real() and imag() functions. The angle or the
argument of a complex number can be found using the function angle() and
the value returned is in radians. The steady state AC analysis is similar to the
DC analysis carried out in a previous sections using nodal and loop analysis
etc. In this case the matrices contain complex numbers as opposed to the real
numbers. The following example illustrates an analysis of a simple circuit with
e sinusoidal driving function.
Example 12 Determine the I
o
in the network given in the gure using nodal
and loop analysis.
1
j1
+
6

0
0
V
2

0
0
1
I
o
1
j1
V
1
V
2
Figure 2.16.
The two equations for the nodal analysis are,
V
1
1 +j
+
V
2
1
+
V
2
1 j
= 2

0
0
V
1
V
2
= 6

0
0
and I
o
= 1 V
2
. The following Matlab code will compute I
o
. Again, similar
to previous cases we convert the set of linearly independent equations into its
matrix form.
% Let v = [v_1 v_2] then the equations in matrix form will be
Y = [1/(1+i) (2-i)/(1-i); 1 -1];
I = [2 -6];
v = inv(Y)
*
I;
Io = 1
*
v(2);
% The answer in Amperes is
Io = 2.5000 - 1.5000i
If loop analysis is used to solve for I
o
, we have the following equations. let us
choose the loop currents as follows. The left most loop with I
1
, the right most
32 MATLAB FOR ENGINEERS
loop with I
3
and the outer most loop with I
2
. Then the loop equations are,
I
1
= 2

0
0
1(I
1
+I
2
) +j1((I
1
+I
2
) + 1(I
2
+I
3
) j1(I
2
+I
3
) = 6

0
0
1I
3
+ 1(I
2
+I
3
) j1(I
2
+I
3
) = 0
Then I
o
= I
3
. The Matlab code to compute this number is given below.
% consider i=[I_1 I_2 I_3] be the loop current matrix.
Z = [1 0 0;1+i 2 1-i;0 1-i 2-i];
V = [-2 6 0];
i = inv(Z)
*
V;
Io = -i(3);
% The answer is given as
Io = 2.5000 - 1.5000i
The problem can also be solved using Thevenin analysis by nding the open cir-
cuit voltage across the 1 resistor where the current I
o
is owing. The analysis
takes a similar path. For example if the source had a phase shift of the formV =
6

45
0
, it has to be converted to Cartesian form using the pol2cart(angle,
radius) function in Matlab. Remember that the angle should be in radians.
The typical function statement would be pol2cart(deg2rad(45),6) for the
conversion. All methods described in the DC analysis section is applicable for
the AC steady state analysis too.
4. VARIABLE FREQUENCY NETWORK
PERFORMANCE
In the previous section analysis was limited to a xed frequency at steady
state. In this section we will examine the performance of electrical networks
when excited from variable-frequency sources. In particular we will discuss
methods of obtaining Bode Plots via Matlab simulations. The rst step toward
simulating a frequency response of a system is to obtain the network function or
the transfer function of the circuit at hand. Since in electrical circuits the inputs
and outputs can be either currents or voltages there are several possibilities
for these transfer functions. The transfer function is obtained by substituting
s = j where is the variable frequency and s the Laplace variable to arrive
at a ratio of two polynomials in s. For example, the transfer function G(s) for
the circuit given in Fig. ?? is given by,
V
o
(s)
V
in
(s)
=
1
LCs
2
+RCs + 1
.
There are some matlab functions which simplify polynomial manipulations
used in frequency response analysis. conv(A,B) will give the convolution of
Signal Processing Using Matlab 33
V
in
(s)
R L
C

V
o
(s)
+
Figure 2.17. Series Resonant Circuit
the polynomials A and B. For example (s + 1) (s + 2) = s
2
+ 3s + 2 can
be easily found by the command conv([1 1],[1 2]) which will result in [1
3 2] which are the coefcients of the polynomial with descending orders of s.
In the same manner a given polynomial can be factored to its roots by using the
command roots(). Using the same example above, roots([1 3 2]) will
result in tt -1, -2 indicating that the polynomial can be factored to (s + 1) and
(s +2). The partial fractions of a rational transfer function can be obtained via
the function residue.
Example 13 Draw the bode plot for the network function
H(j) =
j
(j + 1)(0.1j + 1)
substituting s = j and multiplying the factors in the denominator (conv([1
1],[0.1 1]) we obtain the numerator num = [1 0] and the denominator
den = [0.1 1.1 1.0]. The following matlab code generated the bode plot.
num = [1 0];
den = [0.1 1.1 1.0];
sys = tf(num,den);
bode(sys)
The bode plot is shown in Fig. ?? One can also use the function ltiview to
obtain most of the parameters from the frequency response once the sys =
tf(num,den); command is issued and the system is available in the matlab
workspace (read help le). Using bode with arguments will return the magni-
tude, phase and frequency information rather than provide an output plot. The
bode plot can also be drawn using semilogx command. The magnitude of a
complex number can be found by using the abs function which will give you
the absolute value of the argument.
34 MATLAB FOR ENGINEERS
Frequency (rad/sec)
P
h
a
s
e

(
d
e
g
)
;

M
a
g
n
i
t
u
d
e

(
d
B
)
Bode Diagrams
40
35
30
25
20
15
10
5
0
From: U(1)
10
2
10
1
10
0
10
1
10
2
100
50
0
50
100
T
o
:

Y
(
1
)
Figure 2.18. Bode plot
4.1. DESIGN EXAMPLES
Example 14 The series RLC circuit in Fig. ?? is driven by a variable fre-
quency source. If the resonant frequency of the network is selectedas
0
= 1600
rad/s, nd the values of C.

+
24 cos (t + 30
0
)V
10mH
i(t)
2

v
o
(t)
+
C
Figure 2.19. Series resonant circuit
This example is a design oriented problem as opposed to the regular bode
diagram. The frequency domain Transfer function of the network is given by,
H(j) =
V
o
(j)
V
in
(j)
=
j
R
L
(j)
2
+j
R
L
+
1
LC
.
Since the resonant frequency is given we plot the above transfer function around
the given frequency with different values of C in order to nd the value of C
Signal Processing Using Matlab 35
that gives
0
= 1600 rad/s. This is accomplished by creating a matlab function
with the input variable of the capacitance value.
% The function has to be saved as an m file with the file name
% chosen as the function name.
function [frequency, magnitude] = getC(c)
% The frequency is chosen around 1600 rad/s
w = 1000:10:2000;
% Note that we need to use the . operator in this function
% since the numerator and the denominator are both vectors and
% They have to be divided element-wise to obtain the values of
% the transfer function at different frequencies.
H = (200
*
w
*
j)./(-w.
*
w+200
*
w
*
j+100/c);
magnitude = 20
*
log10(abs(H));
frequency = w;
Then by issuing the command sequence
[frequency, magnitude]=getC(39e-6),
followed by plot(frequency,magnitude) we see that the resonant fre-
quency is approximately at 1600 rad/s. If several of the plots need to be drawn
on the same gure window issue the command hold after the rst plot com-
mand. the gure below illustrates the transfer function response for several
values of C.
1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000
45
40
35
30
25
20
15
10
5
0
42 F
Frequency (rad/s)
A
m
p
l
i
t
u
d
e

(
d
B
)
39 F
35 F
Figure 2.20.
36 MATLAB FOR ENGINEERS
Example 15 A telephone transmission system suffers from 60-Hz interfer-
ence caused by nearby power utility lines. Let us use the network in Fig. ?? to
design a simple notch lter to eliminate the 60-Hz interference using Matlab.
+
v
in

L
C
R
eq
+
v
o
(t)

Figure 2.21. Telephone transmission line


We use the Laplace circuit of Fig ?? to analyze the problem. The voltage
transfer function of the telephone transmission system is given by,
V
o
(s)
V
in
(s)
=
R
eq
R
eq
+
(L/C)
sL + (1/sC)
which can be rewritten as
V
o
(s)
V
in
(s)
=
s
2
+
1
LC
s
2
+
s
R
eq
C
+
1
LC
To design a notch lter that can eliminate the 60-Hz signal we have to look
at the bode plot of the system for some value of R
eq
, L and C. We use the
following Matlab programs in order to do this.
function [magnitude, phase, frequency] = notch60(R,L,C)
numerator = [1 0 1/(L
*
C)];
denominator = [1 1/(R
*
C) 1/(L
*
C)];
system = tf(numerator, denominator);
[magnitude, phase, frequency] = bode(system);
[magnitude, phase, frequency] = notch60(100,50e-3,100e-6);
subplot(2,1,1)
semilogx(frequency,magnitude(1,:))
Signal Processing Using Matlab 37
grid
xlabel(Frequency)
ylabel(Gain)
title(Notch filter for R=100Ohm, L=50mH and C=100MicroF)
The frequency response given in Fig. ??. Note that Matlab provides the fre-
10
2
10
3
10
4
0
0.2
0.4
0.6
0.8
1
Frequency
G
a
i
n
Notch filter for R=100Ohm, L=50mH and C=100MicroF
Figure 2.22. Notch lter response
quencies in radians/sec. Hence the lter frequency for these component values
is given by 420/(2) = 66.8 Hz. Now we can repeatedly change the values
of R
eq
, Land C till we obtain the correct notch frequency at 60-Hz. The design
values for the lter will be R = 100, L = 70mH and C = 100F. The lter
response these values is given in Fig. ??.
10
2
10
3
10
4
0
0.2
0.4
0.6
0.8
1
Frequency
G
a
i
n
Notch filter for R=100Ohm, L=70mH and C=100MicroF
Figure 2.23. Notch lter response for 60-Hz
We could have automated the design process used above by using the following
program sequence.
function [magnitude,phase,frequency] = notch60a(R,Ll,Lh,Cl,Ch,n)
% [magnitude,phase,frequency] = notch60a(R,Ll,Lh,Cl,Ch,n)
38 MATLAB FOR ENGINEERS
% L1 <= L < Lh and Cl <= C <= Ch are the limits of change
% n gives us the number of steps
Lstep = (Lh-Ll)/n;
Cstep = (Ch-Cl)/n;
flag = 0;
for i = 0:n-1
for j = 0:n-1
L = Ll+Lstep
*
i;
C = Cl+Cstep
*
j;
numerator = [1 0 1/(L
*
C)];
denominator = [1 1/(R
*
C) 1/(L
*
C)];
system = tf(numerator, denominator);
[magnitude,phase,frequency] = bode(system);
[Y,I] = min(magnitude(1,:));
F = frequency(I)/(2
*
pi)
if (59.9 <= F) & (F <= 60.1)
subplot(2,1,1)
semilogx(frequency,magnitude(1,:))
grid
xlabel(Frequency)
ylabel(Gain)
title(60-Hz Notch filter)
flag = 1;
break
end
end
if flag==1
break
end
end
In this program we supply a range for both L and C and the number of steps
to sweep these values. Then the two for loops will increment the component
values for n steps till the conditions of the if loop is satised. If it is satised
then the program loops are exited using the break function of Matlab. For
convenience we have converted the frequency to Hz in F.
The next step of the design is to check if the lter is operating as expected.
In order to do this we provide a signal which has two different frequencies
and look at the transient output for conrmation. Hence to demonstrate the
effectiveness of the lter we choose the input voltage,
v
in
(t) = 1 sin[(2)60t] + 0.2 sin[(2)1000t]
Signal Processing Using Matlab 39
Which has a 60-Hz and 1-KHz signal added together. We use the following
Matlab program to simulate the system.
function [Vin,Vout,T] = testFilt(R,L,C,Tstart,Tstop,n)
step = (Tstop-Tstart)/n;
T = Tstart:step:Tstop;
T = T(:); % This command ensures that T is a vector
Vin = sin(2
*
pi
*
60
*
T)+0.2
*
sin(2
*
pi
*
1000
*
T);
Vin = Vin(:);
numerator = [1 0 1/(L
*
C)];
denominator = [1 1/(R
*
C) 1/(L
*
C)];
system = tf(numerator, denominator);
[Vout] = lsim(system,Vin,T);
Then we use the following code segment to plot the results given in Fig. ??.
[Vin,Vout,t] = testFilt(100,69.9e-3,1e-4,0,100e-3,10000);
subplot(2,1,1); plot(t,Vin)
axis([60e-3 100e-3 -1.5 1.5]); grid
subplot(2,1,2); plot(t,Vout)
axis([60e-3 100e-3 -1.5 1.5]); grid
It can be clearly seen that the 60-Hz frequency is attenuated to a very small
value by the notch lter.
5. FOURIER ANALYSIS
Fourier analysis is based on the fact that almost all periodic signals may be
expressed as the sum of sine and cosine terms that are harmonically related.
The usage of this important analysis technique is described below. Since the
response of a linear time invariant system to a single sinusoidal signal is easily
calculated, it is now equally easy, with the aid of super-position, to nd the
system response to a sum of sinusoidal inputs.
5.1. FUNDAMENTALS OF FOURIER ANALYSIS
A continuous-time signal is periodic if
f(t) = f(t T
0
) for all t
where the period is the smallest value of T
0
that satises this equation. The
Fourier series comes in two different forms, Trigonometric and the Exponential
Fourier series.
40 MATLAB FOR ENGINEERS
0.06 0.065 0.07 0.075 0.08 0.085 0.09 0.095 0.1
1.5
1
0.5
0
0.5
1
1.5
Time (s)
A
m
p
l
i
t
u
d
e
V
in
0.06 0.065 0.07 0.075 0.08 0.085 0.09 0.095 0.1
1.5
1
0.5
0
0.5
1
1.5
Time (s)
A
m
p
l
i
t
u
d
e
V
out
Figure 2.24. Input Output simulation
Trigonometric Fourier Series : If f(t) is a periodic function then the trigono-
metric Fourier series of it is given by,
f(t) = a
0
+

n=1
(a
n
cos n
0
t +b
n
sin n
0
t) (2.18)
where,
a
0
=
1
T
0
_
t
1
+T
0
t
1
f(t) dt, a
n
=
2
T
0
_
t
1
+T
0
t
1
f(t) cos n
0
t dt, and
b
n
=
2
T
0
_
t
1
+T
0
t
1
f(t) sin n
0
t dt, with
0
=
2
T
0
.
Exponential Fourier Series : For a periodic function f(t) the exponential
Fourier series is given by,
f(t) =

n=
c
n
e
jn
0
t
where,
c
n
=
1
T
0
_
t
1
+T
0
t
1
f(t)e
jn
0
t
dt and T
0
=
2

0
.
Signal Processing Using Matlab 41
The exponential Fourier series can be derived from the trigonometric series
in the following manner. We rst note the following identities;
cos =
e
j
+e
j
2
and sin =
e
j
e
j
2j
Substituting the above in (??) we derive the exponential Fourier series as fol-
lows,
f(t) = a
0
+

n=1
_
a
n
2
(e
jn
0
t
+e
jn
0
t
)
jb
n
2
(e
jn
0
t
e
jn
0
t
)
_
= a
0
+

n=1
__
a
n
jb
n
2
_
e
jn
0
t
+
_
a
n
+jb
n
2
_
e
jn
0
t
_
= c
0
+

n=1
( c
n
e
jn
0
t
+ c
n
e
jn
0
t
) (2.19)
Where,
c
0
= a
0
, c
n
=
a
n
jb
n
2
, and c
n
=
a
n
+jb
n
2
for n = 1, 2, . . . .
The coefcient c
n
is the complex conjugate of c
n
. Note that,
| c
n
| =
_
a
2
n
+b
2
n
2
= | c
n
|.
It follows that the exponential Fourier series given in (??) can be written as,
f(t) =

n=
c
n
e
jn
0
t
(2.20)
where,
c
n
=
1
T
0
_
t
1
+T
0
t
1
f(t)e
jn
0
t
dt (2.21)
5.2. SPECTRUMOF A PERIODIC WAVEFORM
The frequency spectrum is the plot of the amplitudes of the harmonics versus
frequency. The phase spectrum is the plot of the phase of harmonics versus
the frequency. The expressions for the spectrum can be derived by equating
the expressions obtained for the exponential and trigonometric Fourier series.
Note that the spectrum comes in two forms. The one-sided spectrum derived
via the trigonometric Fourier series and the two-sided spectrum derived from
42 MATLAB FOR ENGINEERS
the exponential Fourier series. The spectrum of f(t) can be obtained in the
following manner. The expression given in (??) can be reduced to,
f(t) = a
0
+

n=1
_
a
2
n
+b
2
n
cos (n
0
t +
n
) = c
0
+

n=1
2|c
n
| cos (n
0
t +
n
)
where
n
= tan
1
_

bn
an
_
. Here n = 1, 2, . . .. Thenthe single-sidedspectrum
is given by,
a
0
= c
0
,
_
a
2
n
+b
2
n
= 2|c
n
|,
n
for n > 0
The double sided spectrum is given by,
a
0
= c
0
, |c
n
|,
n
for n = 0.
In general for real f(t) we have |c
n
| having even symmetry and
n
having
odd symmetry. In some cases the Fourier coefcients are substituted with
D
n
= 2c
n
. From the above discussion it can be seen that if c
n
from (??) is
known the spectrum of the periodic signal can be drawn. The Matlab function
trapzcan be used to compute the integration in (??) to arrive at the coefcients.
5.3. STEADY STATE NETWORK RESPONSE TO
PERIODIC INPUTS
The Fourier series can be used to analyze the steady state response of linear
systems to periodic inputs. Let us assume that a passive network has an impulse
response of h(t) andis fedwith a signal f(t) and the correspondingoutput signal
from the network to be g(t). Then using convolution,
g(t) = h(t) f(t)
=
_

=0
h()f(t )d
=
_

=0
h()

n=
c
n
e
jn
0
(t)
d
=

n=
c
n
e
jn
0
t
_

=0
h()e
jn
0

d
=

n=
c
n
e
jn
0
t
H(jn
0
t) =

n=

d
n
e
jn
0
t
where

d
n
= H(jn
0
) c
n
and H(jn
0
) =
_

=0
h()e
jn
0

. Hence it can be
clearly seen that the output is also periodic with period T
0
and the Fourier series
at the output is simply the Fourier coefcients at the input multiplied by the
network function.
Signal Processing Using Matlab 43
Example 16 Findthe exponential Fourier series of the signal givening.(??).
T
0
2T
0
t
v(t)
V
Figure 2.25. Input Signal
Note that the waveform can be dened as,
v(t) =
V
T
0
t, for 0 t T
0
Then by denition, the Fourier coefcients of an exponential series can be
computed as,
c
n
=
1
T
0
_
T
0
0
v(t)e
jn
0
t
dt =
1
T
0
_
T
0
0
V
T
0
te
jn
0
t
dt. (2.22)
Note that the integral is evaluated for one time period T
0
. i.e. t
1
= 0 for this
case.
c
n
=
V
T
2
0
_
T
0
0
t
d
dt
_
e
jn
0
t
jn
0
_
dt (2.23)
The above expression is valid for n = 0 as n appears in the denominator. For
such a case c
0
has to be computed separately. Using integration by parts one
can arrive at,
c
n
=
V
T
2
0
_
1
jn
0
__
(te
jn
0
t

T
0
0
+
_
T
0
0
e
jn
0
t
dt
_
=
jV
2n
. (2.24)
Also,
c
0
=
1
T
0
_
T
0
0
V
T
0
t dt =
V
2
. (2.25)
44 MATLAB FOR ENGINEERS
The Fourier representation of the waveform in (??) is then given by,
v(t) =
V
2
+

n=
n=0
jV
2n
e
jn
0
t
. (2.26)
We can use the following Matlab code segment to plot the Fourier waveform
given by the above equation. For example Figure ?? gives the approximations
for n = 2 and n = 100. It can be seen that higher the number of terms the
better the approximation is. We have assumed that T
0
= 1 sec and V = 10 V.
function [m,t] = fou1(period,n,time_step)
t = 0:time_step:2
*
period;
w = 2
*
pi/period;
k = 1;
for N = -n:n
if N~=0
m(k,:) = (i
*
10/(2
*
pi
*
N))
*
exp(i
*
N
*
w
*
t);
k = k+1;
end
end
m = sum(m)+10/2;
0 0.5 1 1.5 2
0
2
4
6
8
10
n=2
time (sec)
0 0.5 1 1.5 2
0
5
10
15
n=100
time (sec)
Figure 2.26. Fourier Approximation of a Saw-tooth Waveform
Substituting values for n, the spectrum can be identied as
c
0
=
V
2

0, c
1
=
V
2

2
, and c
1
=
V
2

2
Signal Processing Using Matlab 45
The spectrum of this signal is given in Figure ??. Note the clear differences in
the one-sided and the two-sided spectrum. For the one-sided spectrum you are
essentially drawing the coefcients and phase of,
f(t) = c
0
+

n=1
2|c
n
| cos(n
0
t +
n
)
while for the two sided spectrum it is the magnitude and phase of,
f(t) = c
0
+

n=
n=0
c
n
e
jn
0
t
.
c
0

0 2
0
3
0
magnitude

2 c
1
2 c
2
2 c
3
(a)

0 2
0

0 2
0
c
0
c
1
c
2
c
1
c
2
magnitude

(b)
phase

0 2
0
3
0
(c)

0 2
0

0
2
0
phase

2
(d)
Figure 2.27. Single- and Double- sided spectrum
The same spectrumcanbe obtainedbyusingnumerical integrationvia Matlab
on (??).
function [mCn,pCn,n] = fou1spec(period,n,time_step)
t = 0:time_step:period;
46 MATLAB FOR ENGINEERS
w = 2
*
pi/period;
k = 1;
for N = -n:n
y = (10/period^2)
*
t.
*
exp(-i
*
N
*
w
*
t);
c(k) = trapz(t,y);
k = k+1;
end
mCn=abs(c);pCn=180
*
angle(c)/pi;
The Amplitude and phase spectrum can be plotted using the following com-
mands
% double sided amplitude spectrum
subplot(2,2,1); stem([-n:n],mCn)
% double sided phase spectum
subplot(2,2,3); stem([-n:n],pCn)
% single sided magnitude spectum
subplot(2,2,2); stem([0:n],[mCn(n+1) 2
*
mCn(n+2:2
*
n+1)])
% single sided phase spectrum
subplot(2,2,4); stem([0:n],pCn(n+1:2
*
n+1))
The output of the above segment is given in Figure ??.
The two Matlab programs could be combined to simulate the complete com-
putation using the following code segment.
function [F,mCn,pCn,n,tf] = fou1Full(period,n,time_step)
tc = 0:time_step:period;
tf = 0:time_step:2
*
period;
w = 2
*
pi/period;
k = 1;
for N = -n:n
y = (10/period^2)
*
tc.
*
exp(-i
*
N
*
w
*
tc);
c(k) = trapz(tc,y);
F(k,:) = c(k)
*
exp(i
*
N
*
w
*
tf);
k = k+1;
end
F = sum(F);
mCn=abs(c);pCn=180
*
angle(c)/pi;
The complex number multiplications sometimes leave a small residue of imag-
inary values as a result of computation error. Hence a warning is issued that
the imaginary parts are ignored when plotting the function. In order to avoid
this replace F = sum(F); with F = real(sum(F));.
Signal Processing Using Matlab 47
2 1 0 1 2
0
1
2
3
4
5
6
Double sided Spectrum
n
M
a
g
n
i
t
u
d
e
2 1 0 1 2
100
50
0
50
100
n
P
h
a
s
e
0 0.5 1 1.5 2
0
1
2
3
4
5
6
Single Sided Spectrum
n
M
a
g
n
i
t
u
d
e
0 0.5 1 1.5 2
0
20
40
60
80
100
n
P
h
a
s
e
Figure 2.28. Spectrum
If the waveformin(??) is nowusedas aninput tothe circuit giveninFigure ?? we
can nd the expression for v
o
(t) using the Fourier analysis technique. Assume
T
0
= 0.5, V = 2, R = 1 and C = 1F. From the given values we can deduce
v
i
(t)
R
C v
o
(t)
Figure 2.29. RC Circuit
that c
0
= 1 and
0
= 4. The transfer function for all the n
0
frequencies of
48 MATLAB FOR ENGINEERS
the circuit is given by,
H(jn
0
) =
v
o
(jn
0
)
v
i
(jn
0
)
=
1/jn
0
1 + 1/jn
0
=
1
1 +jn
0
=
1
_
1 + (n
0
)
2

tan
1
(n
0
).
Previously we have shown from (??) that,
v
o
(t) =

d
0
+

n=
n=0

d
n
e
jn
0
t
where

d
n
= H(jn
0
) c
n
. Therefore,

d
0
= H(jn
0
)|
n=0
c
0
= 1

0. and at
each n,

d
n
=
_
1
_
1 + (n
0
)
2

tan
1
(n
0
)
_

_
j
n
_
(2.27)
Hence the output signal can now be written as,
v
o
(t) = 1 +

n=
n=0
1
n
_
1 + (n
0
)
2
e
j4nt

2
tan
1
(n
0
)
. (2.28)
The output of the lter can be simulated via Matlab using the following code
segment
function [F,mCn,pCn,n,tf] = fou1output(period,n,time_step)
tc = 0:time_step:period; tf = 0:time_step:2
*
period;
w = 2
*
pi/period;
k = 1;
for N = -n:n
y = (10/period^2)
*
tc.
*
exp(-i
*
N
*
w
*
tc);
c(k) = trapz(tc,y);
d(k) = c(k)
*
(1/(1+i
*
N
*
w));
F(k,:) = d(k)
*
exp(i
*
N
*
w
*
tf);
k = k+1;
end
F = sum(F);
mCn=abs(d);pCn=180
*
angle(d)/pi;
The plot of the output waveform is given in Figure ??.
Exercise 11 Followthe same procedure for the trigonometric Fourier series.
Signal Processing Using Matlab 49
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
2
0
2
4
6
8
10
12
Time (sec)
A
m
p
l
i
t
u
d
e
Figure 2.30. Input output plot for the RC lter
6. FOURIER TRANSFORM
Fourier transform deals with the frequency content of aperiodic signals. The
continuous time Fourier transform of a signal f(t) is dened as
F[f(t)] = F() =
_

f(t)e
jt
dt. (2.29)
F() is a complex function of frequency. The inverse Fourier transform is
given by
F
1
[F()] = f(t) =
1
2
_

F()e
jt
dt. (2.30)
Example 17 Find the Fourier transform of the function
f(x) =
_
1 for 0.5 < x < 0.5
0 otherwise
The Matlab code to compute the Fourier transform is given below
function [M,w] = ftransform(w)
t = -0.5:0.001:0.5;
w = -w:0.5:w;
for N = 1:size(w,2)
if w(N)~=0
m = 1
*
exp(-i
*
w(N)
*
t);
M(N) = trapz(t,m);
else
M(N)=1;
end
end
Exercise 12 Plot the Fourier transform of the sinusoidal signal x(t) =
Acos
a
t, a/2 ta/2.
50 MATLAB FOR ENGINEERS
7. THE LAPLACE TRANSFORM
This section focuss on obtaining Laplace transforms when the time domain
equation is given and the inverse Laplace transforms when the transfer function
is given. The rst method of analysis is using the Symbolic math Toolbox from
matlab. The variables that are used in symbolic math have to be dened as
symbolic using the sym or syms command. The frequently used command of
the symbolic toolbox can be viewed by issuing the command help symbolic.
Example 18 If f(t) = e
at
sint u(t 1), nd F(s).
The symbolic toolbox does not allow the u(t 1) function to be simulated.
Hence we use f(t + 1) = e
a(t+1)
sin (t + 1) u(t) instead and use the shift
theorem to get the nal answer.
sym a t w;
laplace((exp(-a*(t+1))*sin(w*(t+1)));
This will return the following
ans =
exp(-a)*((s+a)*sin(w)+w*cos(w))/((s+a)^2+w^2)
If its required to see this in a more convenient fashion
pretty(ans)
exp(-a) ((s + a) sin(w) + w cos(w))
-----------------------------------
2 2
(s + a) + w
Multiplying this answer by exp(-s) to accommodate the time
shift we arrive at the final answer.
Example 19 Find the inverse laplace transform of,
F(s) =
s
2
+ 4s + 5
(s + 1)(s + 4)
.
sym s
ilaplace((s^2+4*s+5)/(s^2+5*s+4))
The Dirac function is the delta function.
ans = Dirac(t)-5/3*exp(-4*t)+2/3*exp(-t)
The pretty function in Matlab can be used to see the answers little bit more
clearly. If one needs to simplify the equation or combine elements of a solution
given by matlab, you can use the simplify command.
Signal Processing Using Matlab 51
8. CONVOLUTION INTEGRAL VIA MATLAB
The convolution of two data vectors can be carried out using the conv func-
tion in matlab.
Example 20 Plot the convolution of two rectangular pulses of 1s and 2s
duration with equal amplitudes.
This is the time vector for computations
t = 0:0.01:2;
A rectangular pulse can be simulated with rectpuls
f1 = rectpuls(t,2);
f2 = rectpuls(t,4);
p = conv(f1,f2);
A new time vector needs to be calculate with the same step
size as the original waveforms
tp = 0:0.01:0.01*(size(p,2)-1);
subplot(2,2,1); plot(t,f1);grid
title(f_1(t)); xlabel(time (s))
subplot(2,2,2); plot(t,f2);grid
title(f_2(t)); xlabel(time (s))
subplot(2,1,2); plot(tp,p);grid
title(f_1(t)*f_2(t)); xlabel(time (s))
The plot of the convolution obtained from the above code segment is given in
Fig. ??.
Example 21 Plot f(t) using the convolution function if,
F(s) =
1
(s + 1)(s + 2)
.
We use the property F
1
(s)F
2
(s) f
1
(t) f
2
(t).
% \begin{Verbatim}[fontfamily=courier,fontseries=b,frame=single,framerule=1mm]
The initial part is done using symbolic math toolbox
syms s
f1 = ilaplace(1/(s+1));
f2 = ilaplace(1/(s+2));
We have used a time interval of 5 seconds to form the signal
vector.
t = 0:0.01:5;
The eval function will evaluate the symbolic function at the
time intervals specified by t. Note that the symbolic math
toolbox returns the answer with respect to a variable t
52 MATLAB FOR ENGINEERS
0 0.5 1 1.5 2
0
0.2
0.4
0.6
0.8
1
f
1
(t)
time (s)
0 0.5 1 1.5 2
0
0.2
0.4
0.6
0.8
1
f
2
(t)
time (s)
0 0.5 1 1.5 2 2.5 3 3.5 4
0
20
40
60
80
100
f
1
(t)*f
2
(t)
time (s)
Figure 2.31.
f1 = eval(f1);
f2 = eval(f2);
p = conv(f1,f2);
After a convolution the time interval is the addition of the
time intervals of the individual waveforms. the size function
returns the size f the vector\or in [row column] format
tp = 0:0.01:0.01*(size(p,2)-1);
subplot(2,2,1); plot(t,f1);grid
title(f_1(t)); xlabel(time (s))
subplot(2,2,2); plot(t,f2);grid
title(f_2(t)); xlabel(time (s))
subplot(2,1,2); plot(tp,p);grid
title(f_1(t)*f_2(t)); xlabel(time (s))
The plot obtained from the above code segment is shown in Fig. ??.
9. INITIAL AND FINAL VALUE THEOREMS
The initial values and he nal values of a function can be found by using the
symbolic math toolbox to simulate the denitions of the theorem.
Example 22 Find the initial and nal values for the function
F(s) =
10(s + 1)
s(s
2
+ 2s + 2)
Signal Processing Using Matlab 53
0 1 2 3 4 5
0
0.2
0.4
0.6
0.8
1
f
1
(t)
time (s)
0 1 2 3 4 5
0
0.2
0.4
0.6
0.8
1
f
2
(t)
time (s)
0 1 2 3 4 5 6 7 8 9 10
0
5
10
15
20
25
30
f
1
(t)*f
2
(t)
time (s)
Figure 2.32.
and the corresponding time function
f(t) = 5 + 5

2e
t
cos (t 135
0
).
The following code segment will provide the answer to the above example.
By simulating the transfer function
syms s
F = 10*(s+1)/(s*(s^2+2*s+2));
initial = limit(s*F,s,inf);
final = limit(s*F,s,0);
simulating the time domain equation
t = 0:0.01:10;
f = 5+5*sqrt(2)*exp(-t)*cos(t-deg2rad(135));
plot(t,f)
xlabel(time (s))
ylabel(f(t))
from the figure one can identify the initial and the final
values
Fromthe plot in Fig. ?? we can see that f(t = 0) = 0 and the steady state value
(nal value) is 5.
Chapter 3
TRIALS
state transition algorithm {
for each neuron j {0, 1, . . . , M 1}
{
calculate the weighted sum S
j
using Eq. (6);
if (S
j
> t
j
)
{turn ON neuron; Y
1
= +1}
else if (S
j
< t
j
)
{turn OFF neuron; Y
1
= 1}
else
{no change in neuron state; y
j
remains unchanged;} .
}
}
55
Index
Graphics, 1 Numerically, 1
57

You might also like