P. 1
Matlab

Matlab

|Views: 239|Likes:
Published by Niranda Perera

More info:

Published by: Niranda Perera on Sep 06, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

04/15/2014

pdf

text

original

Sections

  • 1. DCANALYSISOFELECTRICCIRCUITS
  • 2.1. DIFFERENTIALEQUATIONREPRESENTATION OFCIRCUITS
  • 2.2. LAPLACETRANSFORMMETHODSFOR TRANSIENTANALYSIS
  • 2.3. TRANSIENTANALYSISEXAMPLES
  • 2.4. DESIGNEXAMPLES
  • 3. ACSTEADYSTATEANALYSIS
  • 4.1. DESIGNEXAMPLES
  • 5.1. FUNDAMENTALSOFFOURIERANALYSIS
  • 5.2. SPECTRUMOFAPERIODICWAVEFORM
  • 5.3. STEADYSTATENETWORKRESPONSETO PERIODICINPUTS
  • 6. FOURIERTRANSFORM
  • 7. THELAPLACETRANSFORM
  • 8. CONVOLUTIONINTEGRALVIAMATLAB
  • 9. INITIALANDFINALVALUETHEOREMS

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 defined 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 find 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
specific 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 defined previously. If previously undefined
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 defined as symbolic variables. Symbolic variables can be defined 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 m×n 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 file. This is a
text file 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-files 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
file should be saved in a file 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 file to display T if a ≥ b and display F otherwise using the
IF-ELSE construct.
Exercise 6 Use the FOR-loop construct to find 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 file 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
predefined 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
figure 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 defined 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 significant 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 file 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 first 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 +jωL +
1
jωC
If L = 4H and C = 1µF,
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
final 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 find 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 first 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 first or second or-
der differential equation respectively. Our analysis will involve finding 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 defined using [Start:
Step: Stop] and use matrix manipulations on the equation to find 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 first-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
n−1
x(t)
dt
n−1
).
Then the above equation can be written as a system of first order equations by
making the substitutions
x
1
= x, x
2
=
dx
dt
, . . . , x
n
=
d
n−1
x
dt
n−1
.
Signal Processing Using Matlab 13
The result is an equivalent system of n first order ODE’s 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 first order ODE’s, 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 first-order transient circuit with one storage element can be represented
by a first 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 definition 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 definition
file 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 first order
ODE case. However in this case the initial conditions will have two values.
The values of dy that is returned from the differential definition 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
n−1
d
n−1
y
dt
n−1
+. . . +a
0
y = b
m
d
m
y
dt
m
+b
m−1
d
m−1
y
dt
m−1
+. . . +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
m−1
s
m−1
+· · · +b
0
a
n
s
n
+a
n−1
s
n−1
+· · · +a
0
.
The above expression can be entered into Matlab as a numerator and denomi-
nator polynomials given by
num = [a
n
a
n−1
. . . a
0
] and den = [b
m
b
m−1
. . . b
0
].
Note that the coefficients 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 define 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 = 1µF 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 final 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 file 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
flowing 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 indefinitely. Plot the current flow 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

t
τ
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

t−1
τ
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 figure 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Ω
100µF
.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 definition 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
fixed value input. However the analysis methods available can still be used to
find 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 definition 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 defined 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 first order ODE’s
˙ 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
+. TOfindthe initial condition for x
2
we turnbacktothe original equation
v
L
+v
R
+v
C
= 6
Substituting the initial conditions we find
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 figure). 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 first
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 finding 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 flipped 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 first 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 specifications are satisfied. 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 definition 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 find 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 figure 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 finding the open cir-
cuit voltage across the 1Ω resistor where the current I
o
is flowing. 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 fixed 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 first 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 coefficients 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ω + 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 file). 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, find 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ω)
=

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 find 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 figure window issue the command hold after the first plot com-
mand. the figure 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 filter 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 filter 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 fi lter response
quencies in radians/sec. Hence the filter 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 filter will be R = 100, L = 70mH and C = 100µF. The filter
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 fi 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 satisfied. If it is satisfied
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 filter 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 confirmation. Hence to demonstrate the
effectiveness of the filter 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 filter.
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 find 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 satisfies 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
=

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
=

ω
0
.
Signal Processing Using Matlab 41
The exponential Fourier series can be derived from the trigonometric series
in the following manner. We first note the following identities;
cos θ =
e

+e
−jθ
2
and sin θ =
e

−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 coefficient ˜ 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 coefficients 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 coefficients.
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−τ)

=

n=−∞
˜ c
n
e
jnω
0
t
_

τ=0
h(τ)e
−jnω
0
τ

=

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 coefficients at the input multiplied by the
network function.
Signal Processing Using Matlab 43
Example 16 Findthe exponential Fourier series of the signal giveninfig.(??).
T
0
2T
0
t
v(t)
V
Figure 2.25. Input Signal
Note that the waveform can be defined as,
v(t) =
V
T
0
t, for 0 ≤ t ≤ T
0
Then by definition, the Fourier coefficients 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
2πn
. (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
2πn
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 identified as
˜ c
0
=
V
2

0, ˜ c
1
=
V

π
2
, and ˜ c
−1
=
V


π
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 coefficients 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

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
ω
π
2
ω
0 2ω
0

0
(c)
ω
0 2ω
0
−ω
0
−2ω
0
phase
ω
π
2
−π
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 find 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

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

n=−∞
n=0
1

_
1 + (nω
0
)
2
e
j4πnt±
π
2
−tan
−1
(nω
0
)
. (2.28)
The output of the filter 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 fi 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 defined as
F[f(t)] = F(ω) =
_

−∞
f(t)e
−jωt
dt. (2.29)
F(ω) is a complex function of frequency. The inverse Fourier transform is
given by
F
−1
[F(ω)] = f(t) =
1

_

−∞
F(ω)e
jωt
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 focus’s on obtaining Laplace transforms when the time domain
equation is given and the inverse Laplace transforms when the transfer function
is given. The first method of analysis is using the Symbolic math Toolbox from
matlab. The variables that are used in symbolic math have to be defined 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
sinωt u(t −1), find 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 final 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 final values of a function can be found by using the
symbolic math toolbox to simulate the definitions of the theorem.
Example 22 Find the initial and final 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
(final 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

Contents

v

List of Figures vii .

.

List of Tables ix .

.

KULASEKERE xi .C.Preface E.

To all those who supported .

Acknowledgments To the different authors xiii .

.

xv . to be written.Foreward Forward text.

.

Introduction Test xvii .

.

(3) lookfor ‘<regular expression>’ :. Any command issued at the command prompt would be executed immediately and the result displayed. help plot gives help on the plot command. A subset of commands given in Maple V symbolic math package made available to the Matlab core. hence in most cases numerical values for the variables should be defined prior to being used in a Matlab function. Matlab also has limited support for non-numerical or symbolic computations. However. If the command is followed by ‘. The following commands can be issued to gain access to this facility: (1) help <function name> :. For example. INTRODUCTION The Matlab program is specially designed for matrix computations: solving systems of linear equations. It also has a built in graphics package for visualization. Matlab command window is ready to accept command line function arguments when the >> prompt is displayed.’ the result is not displayed. Matlab comes with extensive online help facility. (2) doc :. Note that the regular expression should be enclosed in single quotes if the expression has more than one word.This command will initiate a substring search of all the Matlab functions and return the results. Matlab is designed to solve problems numerically.If the function name is known this command returns a detail online help page for that function. factoring matrices and so forth. 1 .Chapter 1 INTRODUCTION TO MATLAB 1.Issuing this command at the Matlab command prompt will initialize the html help database and open the web browser window.

g. A=[1 2. Matrices are introduced into Matlab as a set of numbers enclosed in square brackets (e. a two dimensional array represents a matrix and multi-dimensional arrays represents a multi-dimensional matrix. A matrix of complex numbers can be written as A=[1+2i 3+i. A regular Matlab expression is of the form variable=expression. The variables in the Matlab workspace can be viewed by issuing the command who.3 4]) where the semi-colon . a n-dimensional vector is a n × 1 matrix and so on. For example a one dimensional array represents a vector (e. Hint:– Use lookfor complex to find the commands to be use. A scalar is a 1 × 1 matrix. The matrix so entered will be displayed as shown below. 1+4i 5+i6] and will be displayed as. MATRICES IN MATLAB The basic data type in Matlab is and n-dimensional array of double precision numbers. marks the end of a row. A = 1+2i 1+4i 3+i 5+6i Exercise 3 Find the real part and the imaginary part of the complex number matrix given above. Symbolic variables can be defined by . A specific variable can be cleared by issuing the command clear <variable name>. What is the number of rows and columns in A? An example of a complex number in Matlab is a = 1+2i. Exercise 2 The size of a matrix can be found by issuing the command size(A). A = 1 3 2 4 Exercise 1 The transpose of a matrix is given by B = A’. The expression consists of other variables defined previously. These variable values can be cleared by issuing the command clear.g.2 MATLAB FOR ENGINEERS 2. [1 2 3]). Variables in the expression should evaluate to numerical values or else they should be defined as symbolic variables. If previously undefined variables are used you will see the error message ??? Undefined function or variable ’<missing variable>’.

All Matlab operations are sensitive to the size of the matrix and will return an error message if there are any incompatibilities.3 4]. A(1:2. A(2. (i) create vectors and matrices.1)=[1+2i 1+4i]’.*[1 2. (ii) specify sub-matrices or vectors. The colon symbol (:) is one of the most important operators in Matlab.3 4]=[1 4. It can be used to. for i = 1:4. eg.Introduction to Matlab 3 the sym <variable> command (see help on sym). . The general form of a sub-matrix notation is A(start_row_index:end_row_index. The colon operator can also be used to extract sub-matrices in the following manner.columns) produces a matrix with all the elements being zero.start_col_index:end_col_index) Some special matrices that Matlab can generate are shown below. ones(rows. a = 1:6. Note that the index into a Matlab matrix cannot be zero or negative. Exercise 4 Find the square of the center 3-by-3 matrix from a 5-by-5 matrix of your choice. zeros(rows.columns) produces a matrix with all the elements being unity. The same argument holds for addition.1)=1+4i for the complex matrix given above. The only instance where the matrix sizes are not an issue is when scalar operations (matrix of size 1 × 1) are involved. A(1:2.column). ∗ and so on. eg.3 4]*[1 2. For example. The period (‘.9 16]. For example num is different from Num.15 22] however [1 2. Individual matrix and vector entries can be referenced with indices enclosed in parentheses. For example [1 2. These will be discussed in detail later in this section. For example a 2 × 4 matrix cannot be added to a matrix of size 2 × 3. eye(n) produces a n-dimensional identity matrix.3 4]=[7 10. The same procedure applies to all other operators as well. The period operation has multiplied [1*1 2*2. The general form of the notation is A(row.’) converts an operator into an element wise operation. subtractions and divisions of matrices. −.3:4) is a sub-matrix. eg. (iii) perform iterations.3*3 4*4] rather than treating it as a matrix multiplication. Matlab uses all the standard operators such as +. Remember that a m × n matrix can only be multiplied by a matrix of size n × p. Matlab variable names are case sensitive.

... ... This is a text file with the extension . % The IF statement if expression1 statements containing previously defined Matlab variables elseif <a logical or conditional expression> statements containing previously defined Matlab variables .4 MATLAB FOR ENGINEERS 3.. A further improvement to this can be obtained by writing the script with input output capabilities... The outputs and inputs are a set of comma separated variable values which can be used to reference the computations within the function. else statements containing previously defined Matlab variables end % FOR loop for n = Start:Step:End statements containing previously defined Matlab variables .m. Matlab offers all the standard constructs.. PROGRAMMING IN MATLAB A Matlab expression entered at the command line will get processed immediately and the resulting output will be displayed.. end . The function file should be saved in a file with the same name as the function name and with extension ..m... .. % End of help information ..... Note that the newly created m-files should be in your path.. such as loops and conditionals that are available in other programming languages. function [output variables] = function_name(input variables) % help text for the function % The percentage sign indicates the beginning of a % comment or remark. variables and expressions . % . for complex or longer sequences of program code we can use a Matlab script file. However.. % ..

abs. Exercise 5 Given two integers a and b. input numbers if (min(min(a)) < min(min(b))) s = a. function [s] = compare(a. log. Some of the vector functions available in Matlab are max. Redo the exercise using the WHILE-loop construct. atan.Introduction to Matlab 5 % WHILE loop while <logical or conditional loop terminating criteria> statements containing previously defined Matlab variables . == (logical equal). <=. exp. The following code segment should be saved in a Matlab file named compare. min. acos. sum. tan.m. Matlab also provides scalar functions like sin. Hence the program has to be written to accommodate unequal matrix sizes. . end Nested conditionals are also allowed. Exercise 6 Use the FOR-loop construct to find the sum of integers from 1 to 10.Output variable % a. The conditional or logical expressions use relational (or logical) operators such as <. else s = b. Note that the problem does not state the matrix size.. any and all. To obtain the smallest element in a matrix we can use the Matlab min function. end Exercise 7 Write a Matlab function to accept two vectors and return the multiplication of the average values of the two vectors. write a sequence of statements in a Matlab script file to display T if a ≥ b and display F otherwise using the IF-ELSE construct. >. sqrt and round.. asin.b) % s . prod. cos. These are binary operators that return values 0 (False) or 1 (True) for scalar arguments.b. = (logical not-equal) in its construction. sort. >=.b) % Help for compare % [s] = compare(a. Example 1 Write a simple Matlab function to compare two matrices a and b and return the matrix that has the smallest element.

Place text with mouse. axis grid hold axes subplot - Control axis scaling and appearance.Semi-log scale plot.Linear plot. Two dimensional graphs.Semi-log scale plot. Grid lines..x2. Elementary X-Y graphs. To plot a single set of data y vs t the command plot(x. A new figure window can be opened by issuing the command figure(<number>). ylabel .Log-log scale plot.Y-axis label. To plot multiple variables on the same plot we can use the command plot(x1. Some of the graphics commands that will be used in this report are listed below..Graph title. plot .Text annotation. A subset of the possible values are given below. MATLAB PLOTTING COMMANDS Matlab creates xy.xn.. semilogy . One plot can be held on the graph window by issuing the command hold.Graphs with y tick labels on the left and right.polar. Use the Matlab help facility to get more information on the plotting commands.y2.yn).X-axis label.semilog. Graph annotation.y1. The simplest form of a graph is created using the plot command. semilogx .discrete. Hold current graph. plotyy . Matlab has predefined line colors and lines types that can be used to differentiate different plots. Line Types Solid Dash Dotted Dashdot Indicators -: -. xlabel . Create axes in arbitrary positions. loglog . Create axes in tiled positions.and bar graphs.. Point Types Point Plus Star Circle Indicators .y. text . title .6 MATLAB FOR ENGINEERS 4.’:’) would plot the graph with a dotted line. Axis control. . Here both y and x should have the same size. + * o Color Red Green Blue Cyan Symbol r g b c For example plot(x. gtext .y) can be used.

Matlab selects axis limits based on the range of the plotted data.2e−3t V . For example x=ginput(2) command will extract two points from the plot and assign them to x. Call axis with the new limits defined as a four-element vector. Exercise 8 Plot one cycle (2π) of a sine wave.Introduction to Matlab 7 Text can be placed at any position on the plot using the gtext command. For example disp(x) will display the contents of the matrix without the ans= comment. Ctrl-C key sequence will terminate the execution of the current program. Use any text editor to edit the contents in diary. Add axis labels and a title and print. If the break command exists in the inner most part of a nested loop. pi represents the variable π. For example format short will round all Matlab numerical outputs to 5 significant decimal digits. The break command is useful in exiting a loop when an error condition is detected. possibly for printing or inclusion of a report at a later time. disp This command displays a matrix or string without printing its name. For example gtext(’place’) would produce a cross-hair on the plot window which can be used to place the text. OTHER RELEVANT COMMANDS break This command may be used to terminate the execution of FOR and WHILE loops. diary on will activate saving all the key strokes in a file called diary in the current directory and the command diary off terminated the writing process. 5. You can also specify the limits manually using the axis command. Exercise 9 The output voltage of a first order transient circuit is given by vo (t) = 2 − 3. format controls the format of the Matlab output. This can be used as the emergency stop for unwanted operations. ymin. a break statement inside the inner loop will exit from that loop only. Conversely you can use the ginput command to transfer x-y value pairs from the plot window to the Matlab work space. axis([xmin. diary saves a session into a disk. xmax. ymax]) Note that the minimum value should be less that the maximum value.

8
Plot the response using Matlab for t ≥ 0.

MATLAB FOR ENGINEERS

Exercise 10 The equivalent impedance of a circuit 1 is given by
Zeq (jω) = 100 + jωL + If L = 4H and C = 1µF , Plot |Zeq (jω)| vs. ω. What is the minimum impedance? What is the corresponding frequency at this minimum impedance? 1 jωC

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.
v1 2kΩ 6V + − 4kΩ + Vo − 4kΩ 8kΩ v2 8kΩ 2mA

Figure 2.1.

The nodal equations for the above system can be written as, v1 − 6 v1 v1 − v 2 + + =0 2 4 4 v1 − v 2 v2 + −2 = 0 4 8 (2.1) (2.2)

These equations can be converted into [Y ][V ] = [I] format where V is a column vector [v1 v2 ]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 final 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 find 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 Rth = voc /isc to compute the equivalent resistance.

Example 3 Determine Rth at the terminals AB for the network shown in Fig. 2.2.
V1 2kΩ 2000Ix + − 1kΩ Ix B
Figure 2.2.

V2 3kΩ 2kΩ

A

1mA

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, Rth = V2 /1E − 3 will provide the Thevenin resistance. The nodal equations for the circuit are

The peak in the graph corresponds to the maximum power and the associated resistor can be chosen as RL . VS = 10. power is transferred. Example 4 (Maximum Power Transfer Theorem) A 10V DC power source has an internal resistance of 100Ω.Signal Processing Using Matlab 11 given by. % RL: The vactor containing the RL values. % Since the resistors are considered t be in kOhms V is in mV V = inv(Y)*I.P) R = max(P). Design the load resistor R L such that maximum power is transferred. % The answer is 1. plot(RL. TRANSIENT ANALYSIS In this chapter we perform what is known as transient analysis of first and second order circuits via Matlab functions. Y = [4/3 -1/3. Rth = V(2)/1E-3. P = (VS^2*RL). RS = 100. I = [0 1E-3]’. In the next example we will see how Matlab can be used in a design situation to obtain circuit parameters.-1/3 5/6].^2. function [R] = maxpower(RL) % function [R] = maxpower(RL) % R : Resistance at which Max. The circuits we consider will have ./(RS+RL). 2. The following code segments achieves this task. V1 − 2000Ix V1 V1 − V 2 + + =0 2k 1k 3k V2 V2 − V 1 + = 1E − 3 3k 2k V1 Ix = 1k The following code will compute Rth .3kOhms In the above examples Matlab matrix manipulations are used to compute unknown circuit variables.

DIFFERENTIAL EQUATION REPRESENTATION OF CIRCUITS Ordinary differential equations (ODE) often involve a number of dependent variables.e. (3) If the differential form is not known. as well as derivatives of order higher than one. In order to do this a time vector can be defined using [Start: Step: Stop] and use matrix manipulations on the equation to find the values of the function at these time instances. (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. There are several methods available for transient analysis via Matlab.. ).1. (2) If the equation is not known but the differential form is known together with a set of initial conditions. i. Matlab can be used to obtain the time response using the ode23 function. dtn dt dtn−1 Then the above equation can be written as a system of first order equations by making the substitutions x1 = x. x. replace the circuit elements with their Laplace equivalents and obtain the transfer function at the output variable of interest. . We will investigate the application of some of the methods available for transient analysis using several examples in the sections that follow. To use the Matlab ODE solvers. xn = n−1 .. . an equation of the form dx(t) = f (t. . x2 = dn−1 x dx . you must rewrite such equations as an equivalent system of first-order differential equations.12 MATLAB FOR ENGINEERS one or two storage element which can be represented by a first or second order differential equation respectively. dt dt . 2.. x). Our analysis will involve finding circuit equations and plotting the time domain response of a circuit after a sudden change in the network due to switches opening or closing. Matlab can be used to plot the waveform. dt Any ODE can be written in the form dn x(t) dx(t) dn−1 x(t) = f (t. (1) If the equation of the transient is known. . This can then be used together with the impulse function in Matlab to arrive at the output response. ..

x1 . where vo is the output state. This procedure can be extended to the second order transients as well. xn ) dt Once you represent the equation as a system of first order ODE’s. x2 . . . you can code it as a function that the MATLAB ODE solver can use.x). dxn = f (t. The function should be of the form dxdt = odefunction(t. dx(t) + ax(t) = f (t) dt The solution to such a equation is provided by the Matlab function ode23. . The following example illustrates this procedure. .[0 2]. . The solver is called using the statement [t. . The differential definition function for this case is function [dx] = odefunc(t. Then one has to choose the initial conditions and the stop time for the simulation (for more information issue help ode23 at the command prompt) as x=0 and time = [0 2]. A first-order transient circuit with one storage element can be represented by a first order differential equation of the form. Consider the second order ODE given by d2 x(t) dx(t) + a1 + a2 x(t) = f (t) 2 dt dt We choose variables x1 and x2 such that (note that these are function in time) x1 = x and Then dx1 = x2 dt dx2 = −ax2 − bx1 + f (t) dt . vo] = ode23(’odefunc’.x) % help instructions if necessary dx = f(t)-ax.Signal Processing Using Matlab 13 The result is an equivalent system of n first order ODE’s of the form dx1 = x2 dt dx2 = x3 dt .0).

1). 2.2. . In some cases this is also known as the network function of the circuit. . % To ensure that dy is a column vector dy(1) = y(2). a0 ] and den = [bm bm−1 . Then replace the circuit elements with their corresponding Laplace equivalents and then obtain the transfer function as a rational polynomial as shown above. we can write the Matlab differential definition file used by ode23 as function dy = diff1(t. = X(s) an sn + an−1 sn−1 + · · · + a0 The above expression can be entered into Matlab as a numerator and denominator polynomials given by num = [an an−1 .14 MATLAB FOR ENGINEERS If we assume y = [x1 (t) x2 (t)]T . Hence we use the zeros function in Matlab to ensure its correct dimensions. Note that the coefficients should be arranged in descending powers of s. the network function can be represented by H(s) = Y (s) bm sm + bm−1 sm−1 + · · · + b0 .y) dy = zeros(2. dtn dt dt dt where x(t) is the input and y(t) is the output. The initial conditions are found after the circuit state changes when the switch is closed. . . For example if the input output equation is represented by an dn−1 y dm y dm−1 y dn y + an−1 n−1 + . dy(2) = -a*y(2)-b*y(1)+f(t) % Here f(t) has to be defined or should be deterministic. + a0 y = bm m + bm−1 m−1 + . . LAPLACE TRANSFORM METHODS FOR TRANSIENT ANALYSIS The response of a system to initial conditions can also be found using the Laplace transform representation of the circuit. . . + b0 y. Once calls the ODE solver ode32 in the same manner as in the first order ODE case. . b0 ]. However in this case the initial conditions will have two values. . The values of dy that is returned from the differential definition should be a column vector. In what follows we provide several examples which illustrate these modeling procedures. The procedure for simulating the transient response using the Laplace method is as follows. One can use the function lsim in Matlab to simulate the transient response.

4.3.Signal Processing Using Matlab 15 2. R = 100e3. plot(t. % Then the time constant in ms is tau = R*C. Example 5 Assuming Vs = 10V DC source. TRANSIENT ANALYSIS EXAMPLES The simplest form of analyzing a transient circuit is to define a time vector via [Start: Step: Stop] and then compute the values of the transient time domain equation explicitly via matrix manipulations.02s intervals t = 0:0. Then the output voltage V o (t) changes according to. use Matlab to plot the transient voltage across the capacitor. In the absence of additional information we can assume that the capacitor is initially unchanged. Vs = 10. C = 1e-6.3. Vo = Vs*(1-exp(-t/tau)). ODE Method 1 .02:1. % The plot for 1 s with 0. Vo (t) = Vs (1 − e− RC t ) Direct Method One can directly simulate the final equation for V o (t) using the following code segment.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. R + Vs + − C Vo (t) − Figure 2. C = 1µF and R = 100kΩ.

4. . C = 1e-6.6 MATLAB FOR ENGINEERS 0. Now the ODE solver can be used to simulate the output state via the following code segment. function [dy] = diff1(t. We obtain Figure 2. Vs = 10. 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. dy = Vs/(R*C)-y/(R*C).3 is vC VS dvC + = dt RC RC The following code segment can be used to simulate the ODE.y) % Help statement is necessary R = 100e3.y) grid. The following code is saved in a separate file named diff1. [t.4 Time (s) 0.16 Charging of a Capacitor 10 9 8 7 Vo(t) (Volts) 6 5 4 3 2 1 0 0 0.4 again. Vo (t) .8 1 Figure 2.2 0.[0 1]. [0]).y] = ode23(’diff1’.m. plot(t.across the capacitor The ODE governing the circuit in Figure 2.

T). R = 100e3. the initial current flowing through the inductor is zero.2). % Simulating using an explicit input %R = 100e3. sys = tf(num. where τ1 = = 2s. 2. num=[10]. Example 6 For the transient circuit shown in Fig. % 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.5. Plot the current flow through the inductor with respect to time.100). C = 1e-6. Then. T = 0:1/size(U. The transfer function is given by. Direct Method For the time duration 0 < t < 1 sec. den=[R*C 1 0]. % This is the corresponding time % Make sure that the U and T vectors match in length lsim(sys.U. % Simulating the Laplace transformed circuit.den). Vo (s) 1 = . Vs (s) 1 + RCs However if we take Vs (s) = 10/s the system output is then given by the impulse response of the circuit. % will simulate the output state. (2.3) 50 + 50 . sys = tf(num. The DC voltage source is replaced with a step function and the circuit is replaced by its corresponding transfer function. num = [1]. For example Vs (s) corresponds to a step function with amplitude 10V. U = 10*ones(1. % this simulates the step input. where it remains for 1 second. At t = 0 the switch is moved from a to b.den). den = [RC 1]. After which it is moved from b to c where it remains indefinitely.2):1-1/size(U. the equations that governs the current through the inductor is given by.4(1 − e τ1 ). 200 − t i(t) = 0.Signal Processing Using Matlab 17 Laplace Method The circuit in Figure ?? can also be simulated via a Laplace transformed circuit. The following matlab code segment can be used to obtain the output state. C = 1e-6.

01:6. tau1 = 2.6.18 50Ω b t=0 a c 40V + − 150Ω MATLAB FOR ENGINEERS 200H 50Ω Figure 2.5 ) = I0 The circuit equation that governs the transient at t > 1 is given by.i2) grid title(’RL Transient circuit’) xlabel(’Time Sec’) ylabel(’Inductor Current (A)’) The figure for the above code is given in Figure 2. t2 = 1:0. i1 = 0. n = size(t1). At t = 1 the current in the circuit will act as the initial value I 0 for t > 1. where τ2 = 200 = 1s. plot(t1. I0 = i1(n(2)). hold plot(t2. 150 + 50 (2.6 From the Laplace equivalent circuit for 0 ≤ t < 1 the current is 0.i1). i(t) = I0 e − t−1 τ 2 .5. The t = 1 value of the current will act as the initial condition I 0 for the Laplace .01:1. i2 = I0*exp(-(t2-1)/tau2). i(t = 1) = 0.5s We can explicitly simulate this equation using the impulse function.2 I(s) = 2 s + 0.4) The matlab code to plot the transient is given below.4*(1-exp(-t1/tau1)). Laplace Method The above problem can also be solved using the Laplace equivalent circuits shown in Figure 2. % Code to simulate the transient of above example t1 = 0:0. tau2 = 1.4(1 − e−0.

Signal Processing Using Matlab RL Transient circuit 0.04 0.02 0 0 19 1 2 3 Time Sec 4 5 6 Figure 2. .12 Inductor Current (A) 0. The equation for the current will now be governed by I(s) = sI0 200s + 200 The Matlab code to simulate this system is shown below.6.08 0.14 0.16 0. RL Transient 50 200s 40 s + − 50 (a) Circuit for 0 ≤ t < 0 200s sI0 −+ 50 150 (b) Circuit for t ≥ 0 circuit for t ≥ 1.1 0.06 0.

1)). However when the switch opens. The output for t > 0 is given by. The capacitor initial value is 6V .20 MATLAB FOR ENGINEERS % The simulation for system sys1 for 0<= t < 1 sys1 = tf([0.1). plot(T1.1:0 v1 = 6*ones(1.T2] = impulse(sys2.Y2) Example 7 Plot vo (t) for t > 0 in the circuit given below including the time interval just prior to opening the switch. % I0 is the last value in Y1.5 0]).2].7.6). I0 = Y1(size(Y1. % for t > 0 t2 = 0:0.t = 0 6kΩ 12V + − 6kΩ 6kΩ + vo (t) − Figure 2.T2.01:2. the capacitor is an open circuit and vo (t = 0− ) = 12 · 6/(6 + 6).Y1. [Y2. Direct Method For the interval just prior to opening the switch. the output voltage drops to v o (t = 0+ ) = −6 · 6/(6 + 6) = −3V . The capacitor will discharge through an equivalent resistance of 4kΩ.5:0.T1] = impulse(sys1.4 % for the time just prior to the opening of the switch t1=-0. vo (t) = −3e− 0.[200 200]). t . [Y1.[1:0.1:6]). % The simulation for system sys2 for t>= 1 sys2 = tf([I0 0].[1 0. 100µF .

8.5) The above equation has an initial condition given by.v1.t2. The following matlab code can be used to generate the transient response at the output.v0) code has to be saved .v0] = ode23(’diff1’. plot(t. % The differential function used in the % in a separate file called diff1. The differential definition is given by.y) dy = -(5/2)*y.[0 2].5 Time (s) 1 1. Then the output state can be computed by the Matlab ODE solver %issue the commands at the commmand prompt [t.m function dy = diff1(t.-3). The output transient voltage ODE Method The differential equation that governs the circuit behavior for t > 0 is given by.5 2 Figure 2.4).v2) axis([-1 2 -4 7]) % Will center the plot on the window The Matlab plot obtained from the code is given in Fig. v o (t = 0+ ) = −3V. dvo 5 = − vo dt 2 (2.8.5 0 0. 7 6 5 4 3 vo(t) (V) 2 1 0 −1 −2 −3 −4 −1 −0.Signal Processing Using Matlab 21 v2 = -3*exp(-t2/0. plot(t1. 2.

8) (2.9.7) (2. The time domain equation for the output is vo (t) = 24(e−6t − e−4t ).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.6) The code below shows how to solve for the output using the three different methods we have leant so far.01:2. % Using direct computation. Example 8 Find the transient output vo (t) for t > 0 i the circuit given below. However the analysis methods available can still be used to find the transient output. t = 0:0. vo = 24*(exp(-6*t)-exp(-4*t)). dvo + 6vo = −48e−4t dt The Laplace representation of the output voltage is given by. Vo (s) = −48 . In this example it can be seen that the input signal is not a DC source with a fixed value input.vo) The differential definition is given by function dy = diff1(t. 1Ω 12e−4t V − + t=0 500mH 2Ω + vo (t) − Figure 2. plot(t. 2. end . The Fig.y) dy = -6*y-48*exp(-4*t). s2 + 10s + 24 (2. The differential equation that governs the output voltage is found to be.10 shows the output plot from the simulations.

[0 2].01:2.Y) % The Laplace equivalent simulatin sys = tf([-48].5 −1 Amplitude −1.10. t = 0:0. plot(t.5e−2t − 9e−4t .5*exp(-2*t)-9*exp(-4*t). Direct Method The time domain equation for vo (t) is given by.Y] = ode23(’diff1’.v) xlabel(’time (sec)’) . impulse(sys) The simulations result in an output voltage shown in Figure 2.0). Example 9 Find the transient response across the 3Ω resistor.5 −3 −3.9) Since the expression for the vo (t) is known we can simply simulate the transient waveform for a defined time period.5 −4 0 0. v = 13.Signal Processing Using Matlab 23 The differential solver for the above is [T. 0 −0.10. (2. vo (t) = 13. % Choose a time span to simulate the output.5 Time (sec) 1 1.5 −2 −2.[1 10 24]). plot(T.5 Figure 2.

5 2 Figure 2. Transient output across 3Ω 6 5 4 vo(t) (V) 3 2 1 0 0 0.11.12.5 1 time (sec) 1. ??. ylabel(’v_o(t) (V)’) title(’Transient output across 3\Omega’) The output from the above code is given in Fig.24 8Ω − vo + 3Ω MATLAB FOR ENGINEERS 1 4F t=0 1 2H t=0 12V + − + 6V − Figure 2. ODE Method .

DESIGN EXAMPLES Example 10 A simple RLC circuit can be used to model an automobile ignition system1 . % The voltage drop across the 3Ohm resistor is given by plot(t. TO find the initial condition for x 2 we turn back to the original equation vL + v R + v C = 6 Substituting the initial conditions we find di dt = t=0+ 6 − vC (t = 0+ ) − Ri(t = 0+ ) = 3. L The differential solver for a 2 sec.10) We use x1 = i and x2 = di/dt to convert (??) into two first order ODE’s x1 = x2 ˙ x2 = −8x1 − 6x2 ˙ The differential code segment for the above ODE is function dx = diff1(t. . thereby discharging the capacitor through the inductor. % This will ensure that dx(1) = x(2). The internal resistance of the inductor coil (L = 200 mH) is denoted by R and is given to be 4 Ω.y] = ode23(’diff1’.x) dx = zeros(2.[0 2]. [1.Signal Processing Using Matlab 25 If the current in the circuit is i(t) after the switch is closed the ODE that governs the circuit response is given by di d2 i + 6 + 8i = 0. To start the motor the battery is removed via the switch at t = 0. with i(t = 0+ ) = 1.5 and vC (t = 0+ ) = 0. dx(2) = -8*x(1)-6*x(2). dx is a column vector The two initial conditions are x1 (t = 0+ ) = i((t = 0+ ) and x2 (t = 0+ ) = di dt |t=0+ . Initially the battery e(t) = 12V is connected to the series RLC circuit.3*y(:. 2 dt dt (2. time duration given by [t.5 3]). 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 figure).1).1)) 2.4.

First we note that the equation of the circuit after the switch is closed is vc + v L + v R = 0 1 Basic (2. Obtain the design values manually and also via Matlab using the following methods.5 s. David Irwin and Chwan-Hwa Wu. (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. (1) Show that the RLC circuit in Figure ?? can be characterized by two first order differential equations. (4) Verify using Matlab that the system is over damped by finding the damping ratio and the natural frequency. . L and C. Before the switch is closed the capacitor charges up with a current in the clockwise direction in the circuit.11) Engineering Circuit Analysis: J. Also show that these two differential equations can be reduced to an integrator-differential equation of the form.13. This will be discussed as the we proceed. Do the following. (Hint : use roots or damp) We have to take into account the physical status of the starter motor operation and how it effects our analysis. (2) Find The systems characteristic equation and determine the roots in terms of R. We need to account for this sign change in some manner.26 Switch L R MATLAB FOR ENGINEERS i(t) C e(t) + − Figure 2. dy(t) + ay(t) + b dt t y(τ )dτ = x(t) 0 Also show that this equation can be reduced to a second order differential equation. A simple RLC circuit The starter operation requires that the current through the inductor to be over damped. However when the switch is flipped the current in the circuit is reversed when it discharges through the starter coil.

s1 + s 2 = R = 20 L 1 s1 s2 = LC R 1 s+ L LC We now have to choose arbitrary values for s 1 and s2 and draw the current waveform to see if the design specifications are satisfied. let y ≡ [vc .15) L + dt C Differentiating (??) and getting the Laplace transform we get the following characteristic equation.16) s2 + s + L LC Since it is given that the system is over-damped we should have two real and unequal roots. If we substitute for vC from (??) in (??) we get the integro-differential equation 1 di idt + iR = 0 (2. We use (??) to obtain the following: vc + L di + iR = 0 dt di R vC = −i − . (2. function dy = diff1(t.1) % This statement makes sure a vector is returned for . 1 R =0 (2.y) dy = zeros(2. ??. iL ] be our state vector.12) (2. (s + s1 )(s + s2 ) = s2 + (s1 + s2 )s + s1 s2 = s2 + From which we can deduce that.13) and we also note that. Then we have the following. Lets call them s1 and s2 . dvC i = .14) dt C These two first order differential equations will characterize the circuit in Figure. dt L L (2. 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 definition in matlab as follows.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 vC (t = 0+ ) = −12 rather than the positive value before the switch is closed.

The Laplace equivalent circuit is used to find the network function of the circuit or also known as the transfer function of the system. −ζω0 .[6*(C(i)+1) 6 1]). figure(1). figure(2). choose the value of C for critical damping.[0 2]. Substitute the appropriate values for R.z] = sysfind(Cl. Before we proceed any further we note the following: Over-damped system: ζ > 1 and s = −ζω0 ± ω0 Under-damped system: ζ < 1 and s = −ζω 0 ± jω0 ζ 2 − 1. for i = 1:size(C.m.step) C = [Cl:step:Ch].Ch.28 dy(1) = y(2)/C. Hence we carry out the design by changing the values of the capacitor C until the system system damping ration ζ = 1.2) sys = tf([6*C(i) 0 0]. MATLAB FOR ENGINEERS Save the above statements in diff1. function [p. VS (s) (6C + 6)s2 + 6s + 1 (2. . Critically damped system: ζ = 1 and s = −ζω 0 . L and C as the case may be. Example 11 For the circuit given in Figure ??.17) The roots of the denominator polynomial will determine the damping of the system.. Vo (s) 6Cs2 = . 1 − ζ 2.Y] = ode23(’diff1’.14. dy(2) = -y(1)/L-y(2)*R/L. We use the following Matlab program for this purpose.hold. The the function is called by issuing the command [T. C + 1Ω vo (t) − Vs (t) + − 6H 1F Figure 2.[-12 0]).hold.

1.z.9 and step = 0.num2str(C(i))) figure(2) plot(i. For example if we wish to plot the waveform given by v(t) = 10 cos(ωt + 450 ) we will use the following code.33. wt = 0:0.1.z(1).Signal Processing Using Matlab 29 [wn.’x’) % The text statement will enable us to identify the % correct point on the output graphs. transients or natural responses which will eventually vanish at the steady state. In Matlab the angles are assumed to be in radians unless otherwise mentioned. 2C + 2 For critical damping ζ = 1 which implies C = 0.p] = damp(sys). plot(wt. −0. 3.’+’) text(i.33 and the corresponding capacitor value is C = 0. 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. The characteristic polynomial for the given system can be written as 1 1 2 s+ .num2str(C(i))) end We plot the roots of the characteristic equation and the damping factor for Cl=0.5F .v) % the degrees to radians conversion can also be done using a . AC STEADY STATE ANALYSIS In this section we discuss the steady-state forced response of networks with sinusoidal driving functions. text(real(p).imag(p). It can be seen that the Critically damped poles occur at s = −0.5F . Ch = 0. For these analysis types we ignore the effect of initial conditions. v = 10*cos(wt+45*pi/180). In this section we concentrate on the AC behavior of circuits in two stages.imag(p). We now proceed to do the same computation manually in order to illustrate the procedure. The corresponding output graphs are given in Figure ??. s2 + 2ζω0 s + ω0 ≡ s2 + C +1 6C + 6 From which we deduce ω0 = 1 and ζ = 6C + 6 3 .z.01:2*pi. figure(1) plot(real(p).

05 Imaginary 0 0.8 0.05 0.95 0.3 0.40.1 1.2 −0.2 0.2 0.7 (a) Poles of the System 1.1 0.9 0.6 −0.9 −0.85 1 2 3 4 5 6 7 8 9 (b) Damping Ration of the System Figure 2.7 0. % Matlab function.7 0. .8 0.5 0.05 1 0.6 −0.6 0.1 ζ 0.1 0.8 0.15 MATLAB FOR ENGINEERS 0.4 0.5 0.3 0.5 Real −0.1 0.30 0.15. v = 10*cos(wt+deg2rad(45)).9 0.3 0.1 0.15 −0.3 −0.2 −0.6 0.9 0.4 −0.7 0.4 0.

The following example illustrates an analysis of a simple circuit with e sinusoidal driving function.5000i If loop analysis is used to solve for I o .1.16. let us choose the loop currents as follows. j1Ω V1 6 00 V −+ 2 00 V2 1Ω 1Ω 1Ω Io −j1Ω Figure 2. V2 V2 V1 + + = 2 00 1+j 1 1−j V1 − V2 = −6 00 and Io = 1 · V2 . The steady state AC analysis is similar to the DC analysis carried out in a previous sections using nodal and loop analysis etc. % Let v = [v_1 v_2] then the equations in matrix form will be Y = [1/(1+i) (2-i)/(1-i). we have the following equations. 1 -1]. The real part and the complex part of a complex number can be found using real() and imag() functions. The left most loop with I 1 . I = [2 -6]’. the circuit components are replaced by complex numbers. The following Matlab code will compute I o . The two equations for the nodal analysis are. Io = 1*v(2). Example 12 Determine the Io in the network given in the figure using nodal and loop analysis. For example. The angle or the argument of a complex number can be found using the function angle() and the value returned is in radians. Again.5000 . v = inv(Y)*I. the right most . the inductor of value L is represented by jLω where ω is the frequency of operation.Signal Processing Using Matlab 31 In steady state analysis. similar to previous cases we convert the set of linearly independent equations into its matrix form. % The answer in Amperes is Io = 2. In this case the matrices contain complex numbers as opposed to the real numbers.

Z = [1 0 0. Io = -i(3). For example if the source had a phase shift of the form V = 6 450 .1+i 2 1-i. it has to be converted to Cartesian form using the pol2cart(angle.5000i The problem can also be solved using Thevenin analysis by finding the open circuit voltage across the 1Ω resistor where the current I o is flowing. % consider i=[I_1 I_2 I_3] be the loop current matrix. ?? is given by. VARIABLE FREQUENCY NETWORK PERFORMANCE In the previous section analysis was limited to a fixed frequency at steady state.6) for the conversion. For example. Remember that the angle should be in radians. V = [-2 6 0]’. the transfer function G(s) for the circuit given in Fig. The typical function statement would be pol2cart(deg2rad(45).5000 . In this section we will examine the performance of electrical networks when excited from variable-frequency sources. The first step toward simulating a frequency response of a system is to obtain the network function or the transfer function of the circuit at hand. 4. Then the loop equations are. The Matlab code to compute this number is given below. In particular we will discuss methods of obtaining Bode Plots via Matlab simulations.0 1-i 2-i]. Vin (s) LCs2 + RCs + 1 There are some matlab functions which simplify polynomial manipulations used in frequency response analysis. 1(I1 + I2 ) + j1((I1 + I2 ) + 1(I2 + I3 ) − j1(I2 + I3 ) = 6 00 1I3 + 1(I2 + I3 ) − j1(I2 + I3 ) = 0 I1 = −2 00 Then Io = −I3 . 1 Vo (s) = . radius) function in Matlab. The analysis takes a similar path. 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.32 MATLAB FOR ENGINEERS loop with I3 and the outer most loop with I2 . Since in electrical circuits the inputs and outputs can be either currents or voltages there are several possibilities for these transfer functions. i = inv(Z)*V. conv(A.B) will give the convolution of .1. % The answer is given as Io = 2. All methods described in the DC analysis section is applicable for the AC steady state analysis too.

In the same manner a given polynomial can be factored to its roots by using the command roots(). bode(sys) The bode plot is shown in Fig. roots([1 3 2]) will result in tt -1.1jω + 1) substituting s = jω and multiplying the factors in the denominator (conv([1 1].1 1.den).[1 2]) which will result in [1 3 2] which are the coefficients of the polynomial with descending orders of s. Using bode with arguments will return the magnitude. den = [0. The bode plot can also be drawn using semilogx command. -2 indicating that the polynomial can be factored to (s + 1) and (s + 2).Signal Processing Using Matlab 33 R L + Vo (s) − Vin (s) C Figure 2. phase and frequency information rather than provide an output plot.1 1]) we obtain the numerator num = [1 0] and the denominator den = [0. command is issued and the system is available in the matlab workspace (read help file). sys = tf(num. Series Resonant Circuit the polynomials A and B.0]. Example 13 Draw the bode plot for the network function H(jω) = jω (jω + 1)(0.[0.den). The partial fractions of a rational transfer function can be obtained via the function residue. The magnitude of a complex number can be found by using the abs function which will give you the absolute value of the argument.1 1.17. For example (s + 1) × (s + 2) = s 2 + 3s + 2 can be easily found by the command conv([1 1].1 1.1 1. . ?? One can also use the function ltiview to obtain most of the parameters from the frequency response once the sys = tf(num.0]. num = [1 0]. Using the same example above. The following matlab code generated the bode plot.

DESIGN EXAMPLES Example 14 The series RLC circuit in Fig. Magnitude (dB) −25 −30 −35 −40 100 50 To: Y(1) 0 −50 −100 −2 10 10 −1 10 0 10 1 10 2 Frequency (rad/sec) Figure 2. i(t) 10mH + − C Figure 2. ?? is driven by a variable frequency source.1. H(jω) = jω R Vo (jω) L = Vin (jω) (jω)2 + jω R + L .18. find the values of C. The frequency domain Transfer function of the network is given by. If the resonant frequency of the network is selected as ω 0 = 1600 rad/s.34 Bode Diagrams From: U(1) 0 −5 −10 −15 −20 MATLAB FOR ENGINEERS Phase (deg).19. Series resonant circuit 24 cos (ωt + 300 )V + 2Ω vo (t) − This example is a design oriented problem as opposed to the regular bode diagram. 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 find the value of C . Bode plot 4.

the figure below illustrates the transfer function response for several values of C. If several of the plots need to be drawn on the same figure window issue the command hold after the first plot command. followed by plot(frequency. Then by issuing the command sequence [frequency. magnitude]=getC(39e-6).magnitude) we see that the resonant frequency is approximately at 1600 rad/s. function [frequency.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. magnitude = 20*log10(abs(H)). magnitude] = getC(c) % The frequency is chosen around 1600 rad/s w = 1000:10:2000. % Note that we need to use the ’. 0 −5 −10 −15 Amplitude (dB) −20 −25 35µ F −30 39µ F −35 42µ F −40 −45 1000 1100 1200 1300 1400 1500 1600 Frequency (rad/s) 1700 1800 1900 2000 Figure 2.*w+200*w*j+100/c).’ 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). % The function has to be saved as an m file with the file name % chosen as the function name./(-w.20. frequency = w. .

L and C. denominator = [1 1/(R*C) 1/(L*C)].1. Vo (s) = Vin (s) which can be rewritten as Vo (s) = Vin (s) s2 + s2 + 1 LC Req (L/C) Req + sL + (1/sC) s 1 + Req C LC To design a notch filter that can eliminate the 60-Hz signal we have to look at the bode plot of the system for some value of R eq .1) semilogx(frequency. phase. phase. The voltage transfer function of the telephone transmission system is given by. Telephone transmission line + C Req vo (t) − We use the Laplace circuit of Fig ?? to analyze the problem.50e-3. ?? to design a simple notch filter to eliminate the 60-Hz interference using Matlab. frequency] = notch60(100.:)’) . frequency] = notch60(R. frequency] = bode(system). [magnitude.magnitude(1.L.C) numerator = [1 0 1/(L*C)]. [magnitude.21. subplot(2. Let us use the network in Fig. We use the following Matlab programs in order to do this. phase. function [magnitude. L + vin − Figure 2. system = tf(numerator.100e-6).36 MATLAB FOR ENGINEERS Example 15 A telephone transmission system suffers from 60-Hz interference caused by nearby power utility lines. denominator).

4 0. Notch filter response for 60-Hz We could have automated the design process used above by using the following program sequence. Note that Matlab provides the freNotch filter for R=100Ohm.8 Gain 0.8 Gain 0. Notch filter for R=100Ohm.n) % [magnitude. L=50mH and C=100MicroF’) The frequency response given in Fig.n) . L=50mH and C=100MicroF 1 0.6 0.4 0. ??. The design values for the filter will be R = 100.frequency] = notch60a(R. L and C till we obtain the correct notch frequency at 60-Hz. Hence the filter frequency for these component values is given by 420/(2π) = 66.2 0 2 10 3 4 10 Frequency 10 Figure 2.23.Cl.Ch.phase.Lh. L=70mH and C=100MicroF 1 0.2 0 2 10 3 4 10 Frequency 10 Figure 2. Now we can repeatedly change the values of Req . function [magnitude.Ll.Ch. The filter response these values is given in Fig.Lh.phase. Notch filter response quencies in radians/sec.frequency] = notch60a(R.Cl.22.8 − Hz.Signal Processing Using Matlab 37 grid xlabel(’Frequency’) ylabel(’Gain’) title(’Notch filter for R=100Ohm.6 0. ??. L = 70mH and C = 100µF .Ll.

1.9 <= F) & (F <= 60. system = tf(numerator.1) semilogx(frequency.frequency] = bode(system). flag = 0. denominator). For convenience we have converted the frequency to Hz in F . numerator = [1 0 1/(L*C)]. for i = 0:n-1 for j = 0:n-1 L = Ll+Lstep*i.1) subplot(2. 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.2 sin[(2π)1000t] . Hence to demonstrate the effectiveness of the filter we choose the input voltage.:)’) grid xlabel(’Frequency’) ylabel(’Gain’) title(’60-Hz Notch filter’) flag = 1. [magnitude. denominator = [1 1/(R*C) 1/(L*C)]. Then the two for loops will increment the component values for n steps till the conditions of the if loop is satisfied. F = frequency(I)/(2*pi) if (59.:)).magnitude(1. The next step of the design is to check if the filter is operating as expected. [Y. vin (t) = 1 sin[(2π)60t] + 0. In order to do this we provide a signal which has two different frequencies and look at the transient output for confirmation. Cstep = (Ch-Cl)/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. If it is satisfied then the program loops are exited using the break function of Matlab.phase.I] = min(magnitude(1. C = Cl+Cstep*j.

Vin = Vin(:).Tstart. % This command ensures that T is a vector Vin = sin(2*pi*60*T)+0.2*sin(2*pi*1000*T). The usage of this important analysis technique is described below. [Vin. T = Tstart:step:Tstop. Trigonometric and the Exponential Fourier series. The Fourier series comes in two different forms.Signal Processing Using Matlab 39 Which has a 60-Hz and 1-KHz signal added together.T). function [Vin. 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.69.5]). to find the system response to a sum of sinusoidal inputs.1e-4.Vin.T] = testFilt(R.Vin) axis([60e-3 100e-3 -1.1.Vout. . denominator). T = T(:).t] = testFilt(100. with the aid of super-position.1). Since the response of a linear time invariant system to a single sinusoidal signal is easily calculated. system = tf(numerator.Vout) axis([60e-3 100e-3 -1.Vout.C. grid It can be clearly seen that the 60-Hz frequency is attenuated to a very small value by the notch filter.0.9e-3.n) step = (Tstop-Tstart)/n.100e-3. We use the following Matlab program to simulate the system. 5.5]).10000). plot(t. plot(t. numerator = [1 0 1/(L*C)]. FUNDAMENTALS OF FOURIER ANALYSIS f (t) = f (t ± T0 ) for all t A continuous-time signal is periodic if where the period is the smallest value of T 0 that satisfies this equation.Tstop. ??. grid subplot(2.1. denominator = [1 1/(R*C) 1/(L*C)]. Then we use the following code segment to plot the results given in Fig.5 1.1. it is now equally easy. [Vout] = lsim(system. 5.L. subplot(2.5 1.2).

07 0.095 0.085 0.1 Figure 2.5 −1 −1.5 0 −0. Input Output simulation Trigonometric Fourier Series : If f (t) is a periodic function then the trigonometric Fourier series of it is given by.18) where.06 0.09 0.065 0.075 0.09 0.075 0. T0 Exponential Fourier Series : For a periodic function f (t) the exponential Fourier series is given by.1 1. cn = ˜ 1 T0 t1 +T0 t1 f (t)e−jnω0 t dt and T0 = 2π .07 0.5 0.5 0. an = t1 2 T0 t1 +T0 f (t) cos nω0 t dt.095 0.08 Time (s) 0. with ω0 = t1 2π . a0 = 1 T0 t1 +T0 f (t) dt. ∞ f (t) = a0 + n=1 (an cos nω0 t + bn sin nω0 t) (2.5 1 Amplitude 0.24. and t1 bn = 2 T0 t1 +T0 f (t) sin nω0 t dt. ∞ f (t) = n=−∞ cn ejnω0 t ˜ where.5 0 −0.40 Vin 1. ω0 .5 −1 −1.5 1 Amplitude 0.08 Time (s) V out MATLAB FOR ENGINEERS 0.065 0.085 0.06 0.

∞ f (t) = n=−∞ cn ejnω0 t ˜ (2. 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 . and c−n = ˜ for n = 1.Signal Processing Using Matlab 41 The exponential Fourier series can be derived from the trigonometric series in the following manner. SPECTRUM OF A PERIODIC WAVEFORM The frequency spectrum is the plot of the amplitudes of the harmonics versus frequency. . 2.2. c 2 It follows that the exponential Fourier series given in (??) can be written as. cn = ˜ 1 T0 t1 +T0 t1 f (t)e−jnω0 t dt (2. cos θ = ejθ − e−jθ ejθ + e−jθ and sin θ = 2 2j Substituting the above in (??) we derive the exponential Fourier series as follows. We first note the following identities. ˜ ˜ c |˜n | = a2 + b2 n n = |˜−n |. . 2 2 The coefficient c−n is the complex conjugate of cn . The expressions for the spectrum can be derived by equating the expressions obtained for the exponential and trigonometric Fourier series. c0 = a0 . Note that. . . The phase spectrum is the plot of the phase of harmonics versus the frequency. c n = ˜ ˜ an − jbn an + jbn .21) 5. ∞ f (t) = a0 + n=1 ∞ jbn jnω0 t an jnω0 t (e + e−jnω0 t ) − (e − e−jnω0 t ) 2 2 an − jbn 2 ejnω0 t + an + jbn 2 e−jnω0 t (2.19) = a0 + n=1 ∞ = c0 + ˜ n=1 (˜n ejnω0 t + c−n e−jnω0 t ) c ˜ Where.20) where.

. The expression given in (??) can be reduced to.42 MATLAB FOR ENGINEERS the exponential Fourier series. 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. φn for n > 0 n n The double sided spectrum is given by. |cn |. In general for real f (t) we have |cn | having even symmetry and φn having odd symmetry. φn for n = 0. Then the single-sided spectrum n is given by.. Let us assume that a passive network has an impulse response of h(t) and is fed with a signal f (t) and the corresponding output signal from the network to be g(t). . From the above discussion it can be seen that if c n from (??) is known the spectrum of the periodic signal can be drawn. 2.3. The Matlab function trapz can be used to compute the integration in (??) to arrive at the coefficients. a0 = c0 . ∞ ∞ f (t) = a0 + n=1 a2 n + b2 cos (nω0 t n + φn ) = c0 + n=1 2|cn | cos (nω0 t + φn ) b where φn = tan−1 − an . Then using convolution. a0 = c0 . a2 + b2 = 2|cn |. . Here n = 1. g(t) = h(t) ∗ f (t) ∞ = τ =0 ∞ h(τ )f (t − τ )dτ ∞ = τ =0 ∞ h(τ ) n=−∞ cn ejnω0 (t−τ ) dτ ˜ ∞ τ =0 ∞ = n=−∞ ∞ cn ejnω0 t ˜ cn e ˜ n=−∞ jnω0 t h(τ )e−jnω0 τ dτ ˜ dn ejnω0 t n=−∞ ∞ = H(jnω0 t) = ˜ c where dn = H(jnω0 )˜n and H(jnω0 ) = τ =0 h(τ )e−jnω0 τ . 5. 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 coefficients at the input multiplied by the network function. . The spectrum of f (t) can be obtained in the following manner. In some cases the Fourier coefficients are substituted with Dn = 2cn .

t1 = 0 for this case. i.22) The above expression is valid for n = 0 as n appears in the denominator.24) V V t dt = . for 0 ≤ t ≤ T0 T0 Then by definition. v(t) = V t. For such a case c0 has to be computed separately. T0 (2. Using integration by parts one ˜ can arrive at.e. T0 2 (2. cn = ˜ 1 T0 T0 0 v(t)e−jnω0 t dt = 1 T0 T0 0 V −jnω0 t te dt.25) .(??).23) dt −jnω0 T0 0 V 2 T0 1 −jnω0 ( te−jnω0 t T0 0 T0 + 0 e−jnω0 t dt = jV . Input Signal Note that the waveform can be defined as.Signal Processing Using Matlab 43 Example 16 Find the exponential Fourier series of the signal given in fig. 2πn (2. T0 V d e−jnω0 t cn = 2 ˜ t dt (2. the Fourier coefficients of an exponential series can be computed as. v(t) V T0 2T0 t Figure 2. cn = ˜ Also. c0 = ˜ 1 T0 T0 0 Note that the integral is evaluated for one time period T 0 .25.

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

sided spectrum The same spectrum can be obtained by using numerical integration via Matlab on (??).27. . Single. ∞ f (t) = c0 + n=−∞ n=0 cn ejnω0 t .n. Note the clear differences in the one-sided and the two-sided spectrum. function [mCn. For the one-sided spectrum you are essentially drawing the coefficients and phase of.and Double. ˜ magnitude magnitude c0 ˜ 2˜1 c 2˜2 c 2˜3 c ω0 ω c−2 ˜ c−1 ˜ c0 ˜ c1 ˜ c2 ˜ 2ω0 3ω0 −2ω0 −ω0 ω0 2ω0 ω (a) (b) phase π 2 phase −2ω0 −ω0 π 2 ω0 2ω0 ω −π 2 ω0 2ω0 (c) 3ω0 ω (d) Figure 2. ∞ f (t) = c0 + n=1 2|cn | cos(nω0 t + φn ) while for the two sided spectrum it is the magnitude and phase of.pCn.Signal Processing Using Matlab 45 The spectrum of this signal is given in Figure ??.n] = fou1spec(period.time_step) t = 0:time_step:period.

stem([0:n]. In order to avoid this replace F = sum(F).2.mCn. stem([-n:n]. for N = -n:n y = (10/period^2)*t.pCn=180*angle(c)/pi. stem([-n:n].n.1). Hence a warning is issued that the imaginary parts are ignored when plotting the function. c(k) = trapz(tc. c(k) = trapz(t. with F = real(sum(F)).*exp(-i*N*w*t). stem([0:n].pCn. end F = sum(F). mCn=abs(c).2.tf] = fou1Full(period.2..mCn) % double sided phase spectum subplot(2. end mCn=abs(c). k = k+1. for N = -n:n y = (10/period^2)*tc. F(k. The complex number multiplications sometimes leave a small residue of imaginary values as a result of computation error.46 MATLAB FOR ENGINEERS w = 2*pi/period. k = 1.pCn=180*angle(c)/pi.pCn) % single sided magnitude spectum subplot(2. The two Matlab programs could be combined to simulate the complete computation using the following code segment. k = 1.:) = c(k)*exp(i*N*w*tf).time_step) tc = 0:time_step:period. .3).4).pCn(n+1:2 *n+1)) The output of the above segment is given in Figure ??. w = 2*pi/period.y).2.n.*exp(-i*N*w*tc).[mCn(n+1) 2 *mCn(n+2:2*n+1)]) % single sided phase spectrum subplot(2. function [F.2).y). tf = 0:time_step:2*period. The Amplitude and phase spectrum can be plotted using the following commands % double sided amplitude spectrum subplot(2. k = k+1.

R = 1Ω and C = 1F .29. The transfer function for all the nω 0 frequencies of . From the given values we can deduce R vi (t) C vo (t) Figure 2.28.5 1 n 1. Spectrum If the waveform in (??) is now used as an input to the circuit given in Figure ?? we can find the expression for vo (t) using the Fourier analysis technique. RC Circuit that c0 = 1 and ω0 = 4π.Signal Processing Using Matlab Double sided Spectrum 6 5 Magnitude Magnitude 4 3 2 1 0 −2 −1 0 n 1 2 6 5 4 3 2 1 0 0 0.5 Single Sided Spectrum 47 2 100 100 80 Phase −1 0 n 1 2 60 40 20 0 50 Phase 0 −50 −100 −2 0 0. Assume T0 = 0.5 2 Figure 2.5 1 n 1.5. V = 2.

n. ∞ vo (t) = 1 + 1 1 + (nω0 )2 n=−∞ nπ n=0 ej4πnt± 2 −tan π −1 (nω 0) . and at c ˜ each n.pCn=180*angle(d)/pi. The plot of the output waveform is given in Figure ??.n. (2. end F = sum(F). for N = -n:n y = (10/period^2)*tc.time_step) tc = 0:time_step:period.28) The output of the filter can be simulated via Matlab using the following code segment function [F.y). k = k+1. d0 = H(jnω0 )|n=0 · c0 = 1 0.:) = d(k)*exp(i*N*w*tf). mCn=abs(d). F(k. w = 2*pi/period. Therefore. k = 1. Exercise 11 Follow the same procedure for the trigonometric Fourier series. ∞ ˜ vo (t) = d0 + n=−∞ n=0 ˜ dn ejnω0 t ˜ ˜ where dn = H(jnω0 )˜n . H(jnω0 ) = MATLAB FOR ENGINEERS vo (jnω0 ) 1/jnω0 1 = = = vi (jnω0 ) 1 + 1/jnω0 1 + jnω0 1 1 + (nω0 )2 − tan−1 (nω0 ).*exp(-i*N*w*tc). . Previously we have shown from (??) that. d(k) = c(k)*(1/(1+i*N*w)).27) Hence the output signal can now be written as.mCn.48 the circuit is given by. ˜ dn = 1 1 + (nω0 )2 − tan−1 (nω0 ) · j nπ (2.tf] = fou1output(period.pCn. c(k) = trapz(tc. tf = 0:time_step:2 *period.

The inverse Fourier transform is given by ∞ 1 F (ω)ejωt dt. else M(N)=1. for N = 1:size(w.5 0 otherwise The Matlab code to compute the Fourier transform is given below function [M.8 1 Time (sec) 1.4 0.5:0.30.5:w. (2. (2.m). −a/2 ≤ ta/2.2) if w(N)~=0 m = 1*exp(-i*w(N)*t).6 1. FOURIER TRANSFORM Fourier transform deals with the frequency content of aperiodic signals.29) −∞ F (ω) is a complex function of frequency.4 1.001:0.w] = ftransform(w) t = -0.6 0.5. M(N) = trapz(t.2 0. The continuous time Fourier transform of a signal f (t) is defined as ∞ F[f (t)] = F (ω) = f (t)e−jωt dt.2 1. Input output plot for the RC filter 6.5 < x < 0.Signal Processing Using Matlab 12 10 8 Amplitude 6 4 2 0 −2 0 0.8 2 49 Figure 2.30) F −1 [F (ω)] = f (t) = 2π −∞ Example 17 Find the Fourier transform of the function f (x) = 1 for − 0. w = -w:0. . end end Exercise 12 Plot the Fourier transform of the sinusoidal signal x(t) = A cos ωa t.

Hence we use f (t + 1) = e−a(t+1) sin ω(t + 1) u(t) instead and use the shift theorem to get the final answer. 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. Example 18 If f (t) = e−at sin ωt u(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.50 MATLAB FOR ENGINEERS 7. If one needs to simplify the equation or combine elements of a solution given by matlab. . you can use the simplify command. THE LAPLACE TRANSFORM This section focus’s on obtaining Laplace transforms when the time domain equation is given and the inverse Laplace transforms when the transfer function is given. The symbolic toolbox does not allow the u(t − 1) function to be simulated. F(s) = s2 + 4s + 5 . The frequently used command of the symbolic toolbox can be viewed by issuing the command help symbolic. Example 19 Find the inverse laplace transform of. The first method of analysis is using the Symbolic math Toolbox from matlab. laplace((exp(-a*(t+1))*sin(w*(t+1))). find F(s). The variables that are used in symbolic math have to be defined as symbolic using the sym or syms command. sym a t w. (s + 1)(s + 4) sym s ilaplace((s^2+4*s+5)/(s^2+5*s+4)) The Dirac function is the delta function.

xlabel(’time (s)’) subplot(2.1). Note that the symbolic math toolbox returns the answer with respect to a variable t . ??.f2). (s + 1)(s + 2) We use the property F1 (s)F2 (s) ⇐⇒ f1 (t) ∗ f2 (t). This is the time vector for computations t = 0:0. We have used a time interval of 5 seconds to form the signal vector.2. The eval function will evaluate the symbolic function at the time intervals specified by t. p = conv(f1. f2 = rectpuls(t.01*(size(p.grid title(’f_2(t)’).2).fontseries=b. subplot(2.01:5.2).01:2.f2).grid title(’f_1(t)*f_2(t)’). t = 0:0. % \begin{Verbatim}[fontfamily=courier.1. A rectangular pulse can be simulated with rectpuls f1 = rectpuls(t.p).01:0. Example 21 Plot f (t) using the convolution function if. f2 = ilaplace(1/(s+2)). plot(t.Signal Processing Using Matlab 51 8.4). plot(tp.2. plot(t.f1). CONVOLUTION INTEGRAL VIA MATLAB The convolution of two data vectors can be carried out using the conv function in matlab.2). xlabel(’time (s)’) The plot of the convolution obtained from the above code segment is given in Fig. Example 20 Plot the convolution of two rectangular pulses of 1s and 2s duration with equal amplitudes.grid title(’f_1(t)’).frame=single. xlabel(’time (s)’) subplot(2. A new time vector needs to be calculate with the same step size as the original waveforms tp = 0:0.framerule=1mm] The initial part is done using symbolic math toolbox syms s f1 = ilaplace(1/(s+1)).2)-1). F(s) = 1 .

1. f2 = eval(f2).5 1 time (s) 1.2 0 1 0.grid title(’f_2(t)’). xlabel(’time (s)’) The plot obtained from the above code segment is shown in Fig.8 0.4 0.5 1 1. INITIAL AND FINAL VALUE THEOREMS The initial values and he final values of a function can be found by using the symbolic math toolbox to simulate the definitions of the theorem. subplot(2. xlabel(’time (s)’) subplot(2.6 0.01*(size(p.52 f (t) 1 MATLAB FOR ENGINEERS f (t) 2 1 0. f1 = eval(f1).f2). After a convolution the time interval is the addition of the time intervals of the individual waveforms.5 2 100 80 60 40 20 0 0 0. p = conv(f1.p).1).2)-1). xlabel(’time (s)’) subplot(2.f1).5 3 3. Example 22 Find the initial and final values for the function F(s) = 10(s + 1) s(s2 + 2s + 2) .5 4 Figure 2. the size function returns the size f the vector\or in [row column] format tp = 0:0.2).2).grid title(’f_1(t)*f_2(t)’). ??.2.8 0.6 0.grid title(’f_1(t)’).2 0 0 0. plot(t.01:0.5 2 time (s) 2.5 1 time (s) 1. plot(tp.4 0.5 2 f (t)*f (t) 1 2 0 0.f2). 9.31. plot(t.2.

s.8 0.4 0.2 0 0 1 2 3 time (s) 4 5 f (t)*f (t) 1 2 0 1 2 3 time (s) 4 5 30 25 20 15 10 5 0 0 1 2 3 4 5 time (s) 6 7 8 9 10 Figure 2. ?? we can see that f (t = 0) = 0 and the steady state value (final value) is 5.8 0.4 0.Signal Processing Using Matlab f (t) 1 53 f (t) 2 1 0. The following code segment will provide the answer to the above example. final = limit(s*F.s.6 0.01:10.6 0. By simulating the transfer function syms s F = 10*(s+1)/(s*(s^2+2*s+2)).f) xlabel(’time (s)’) ylabel(’f(t)’) from the figure one can identify the initial and the final values From the plot in Fig. plot(t. and the corresponding time function √ f (t) = 5 + 5 2e−t cos (t − 1350 ). f = 5+5*sqrt(2)*exp(-t)*cos(t-deg2rad(135)). simulating the time domain equation t = 0:0.inf).32. initial = limit(s*F.2 0 1 0.0). .

.

. . 1. } } 55 .Chapter 3 TRIALS state transition algorithm { for each neuron j ∈ {0. M − 1} { calculate the weighted sum Sj using Eq. (6). if (Sj > tj ) {turn ON neuron. Y1 = +1} else if (Sj < tj ) {turn OFF neuron.} . Y1 = −1} else {no change in neuron state. . . yj remains unchanged.

.

1 57 . 1 Numerically.Index Graphics.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->