Matlab

72
MATLAB FOR ENGINEERS E.C. KULASEKERE University of Moratuwa Sri Lanka Kluwer Academic Publishers Boston/Dordrecht/London

Transcript of Matlab

Page 1: Matlab

MATLAB FOR ENGINEERS

E.C. KULASEKEREUniversity of MoratuwaSri Lanka

Kluwer Academic PublishersBoston/Dordrecht/London

Page 2: Matlab

Contents

v

Page 3: Matlab
Page 4: Matlab

List of Figures

vii

Page 5: Matlab
Page 6: Matlab

List of Tables

ix

Page 7: Matlab
Page 8: Matlab

Preface

E.C. KULASEKERE

xi

Page 9: Matlab

To all those who supported

Page 10: Matlab

Acknowledgments

To the different authors

xiii

Page 11: Matlab
Page 12: Matlab

Foreward

Forward text, to be written.

xv

Page 13: Matlab
Page 14: Matlab

IntroductionTest

xvii

Page 15: Matlab
Page 16: Matlab

Chapter 1

INTRODUCTION TO MATLAB

1. INTRODUCTIONThe Matlab program is specially designed for matrix computations: solving

systems of linear equations, factoring matrices and so forth. It also has a builtin graphics package for visualization. Matlab is designed to solve problemsnumerically, hence in most cases numerical values for the variables shouldbe defined prior to being used in a Matlab function. However, Matlab alsohas limited support for non-numerical or symbolic computations. A subset ofcommands given in Maple V symbolic math package made available to theMatlab core.

Matlab command window is ready to accept command line function argu-ments when the >> prompt is displayed. Any command issued at the commandprompt would be executed immediately and the result displayed. If the com-mand is followed by ‘;’ the result is not displayed. Matlab comes with extensiveonline help facility. The following commands can be issued to gain access tothis facility:

(1) help <function name> :- If the function name is known this commandreturns 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 initializethe 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 theregular expression should be enclosed in single quotes if the expression hasmore than one word.

1

Page 17: Matlab

2 MATLAB FOR ENGINEERS

2. MATRICES IN MATLABThe 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-dimensionalarrays represents a multi-dimensional matrix. A scalar is a 1 × 1 matrix, an-dimensional vector is a n × 1 matrix and so on.

Matrices are introduced into Matlab as a set of numbers enclosed in squarebrackets (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 23 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 commandsize(A). What is the number of rows and columns in A?

An example of a complex number in Matlab is a = 1+2i. A matrix of complexnumbers can be written as A=[1+2i 3+i; 1+4i 5+i6] and will be displayedas,

A =1+2i 3+i1+4i 5+6i

Exercise 3 Find the real part and the imaginary part of the complex numbermatrix given above. Hint:– Use lookfor complex to find the commands tobe use.

The variables in the Matlab workspace can be viewed by issuing the commandwho. These variable values can be cleared by issuing the command clear. Aspecific 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 undefinedvariables 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 theyshould be defined as symbolic variables. Symbolic variables can be defined by

Page 18: Matlab

Introduction to Matlab 3

the sym <variable> command (see help on sym). Matlab variable names arecase sensitive. For example num is different from Num.

Matlab uses all the standard operators such as +,−, ∗ and so on. All Matlaboperations are sensitive to the size of the matrix and will return an error messageif there are any incompatibilities. Remember that a m × n matrix can only bemultiplied 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 beadded to a matrix of size 2 × 3. The only instance where the matrix sizes arenot an issue is when scalar operations (matrix of size 1 × 1) are involved.

Individual matrix and vector entries can be referenced with indices enclosedin parentheses. The general form of the notation is A(row,column). Forexample, A(2,1)=1+4i for the complex matrix given above. Note that theindex into a Matlab matrix cannot be zero or negative.

The colon symbol (:) is one of the most important operators in Matlab. Itcan 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 (‘.’) convertsan 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 amatrix multiplication. The same procedure applies to all other operators aswell.

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-matrixnotation 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 matrixof your choice.

Page 19: Matlab

4 MATLAB FOR ENGINEERS

3. PROGRAMMING IN MATLABA Matlab expression entered at the command line will get processed imme-

diately and the resulting output will be displayed. However, for complex orlonger sequences of program code we can use a Matlab script file. This is atext file with the extension .m. A further improvement to this can be obtainedby writing the script with input output capabilities. Note that the newly createdm-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 whichcan be used to reference the computations within the function. The functionfile should be saved in a file with the same name as the function name andwith extension .m. Matlab offers all the standard constructs, such as loops andconditionals that are available in other programming languages.

% The IF statementif expression1statements containing previously defined Matlab variables

elseif <a logical or conditional expression>statements containing previously defined Matlab variables

....elsestatements containing previously defined Matlab variables

end

% FOR loopfor n = Start:Step:Endstatements containing previously defined Matlab variables...

end

Page 20: Matlab

Introduction to Matlab 5

% WHILE loopwhile <logical or conditional loop terminating criteria>statements containing previously defined Matlab variables...

end

Nested conditionals are also allowed. The conditional or logical expressions userelational (or logical) operators such as <, >, <=, >=, == (logical equal), =

(logical not-equal) in its construction. These are binary operators that returnvalues 0 (False) or 1 (True) for scalar arguments.

Exercise 5 Given two integers a and b, write a sequence of statements ina Matlab script file to display T if a ≥ b and display F otherwise using theIF-ELSE construct.

Exercise 6 Use the FOR-loop construct to find the sum of integers from 1 to10. 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 functionsavailable in Matlab are max, min, sort, sum, prod, any and all.

Example 1 Write a simple Matlab function to compare two matrices a andb 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 tobe written to accommodate unequal matrix sizes. The following code segmentshould 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 numbersif (min(min(a)) < min(min(b)))s = a;

elses = b;

end

Exercise 7 Write a Matlab function to accept two vectors and return themultiplication of the average values of the two vectors.

Page 21: Matlab

6 MATLAB FOR ENGINEERS

4. MATLAB PLOTTING COMMANDSMatlab creates xy- polar- semilog- discrete- and bar graphs. The simplest

form of a graph is created using the plot command. Use the Matlab helpfacility to get more information on the plotting commands. Some of the graphicscommands 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. Hereboth y and x should have the same size. To plot multiple variables on the sameplot we can use the command plot(x1,y1,x2,y2,...,xn,yn). One plotcan be held on the graph window by issuing the command hold. Matlab haspredefined line colors and lines types that can be used to differentiate differentplots. A subset of the possible values are given below.

Line Types Indicators Point Types Indicators Color Symbol

Solid - Point . Red rDash -- Plus + Green gDotted : Star * Blue bDashdot -. Circle o Cyan c

For example plot(x,y,’:’) would plot the graph with a dotted line. A newfigure window can be opened by issuing the command figure(<number>).

Page 22: Matlab

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 windowwhich 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 workspace. For example x=ginput(2) command will extract two points from theplot and assign them to x.

Matlab selects axis limits based on the range of the plotted data. You canalso specify the limits manually using the axis command. Call axis with thenew 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 titleand print.

5. OTHER RELEVANT COMMANDSbreak 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 anested loop, a break statement inside the inner loop will exit from that looponly. The break command is useful in exiting a loop when an error conditionis detected.

dispThis command displays a matrix or string without printing its name. Forexample disp(x) will display the contents of the matrix without the ans=comment.

format controls the format of the Matlab output. For exampleformat 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 areport at a later time. diary on will activate saving all the key strokes ina file called diary in the current directory and the command diary off

terminated the writing process. Use any text editor to edit the contents indiary.

Ctrl-C key sequence will terminate the execution of the current program. Thiscan be used as the emergency stop for unwanted operations.

Exercise 9 The output voltage of a first order transient circuit is given by

vo(t) = 2 − 3.2e−3t V

Page 23: Matlab

8 MATLAB FOR ENGINEERS

Plot the response using Matlab for t ≥ 0.

Exercise 10 The equivalent impedance of a circuit1 is given by

Zeq(jω) = 100 + jωL +1

jωC

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?

1Electronics and Circuit Analysis using Matlab by J. Attia

Page 24: Matlab

Chapter 2

SIGNAL PROCESSING USING MATLAB

1. DC ANALYSIS OF ELECTRIC CIRCUITSIn 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 toobtain a set of linearly independent circuit equations which then can be solvedusing matrix manipulations in Matlab.

Example 2 For the circuit shown in Fig. 2.1, obtain the voltage drop Vo

across the 4kΩ resistor.

−+6V

2kΩ

4kΩ

4kΩ

+ Vo−

8kΩ

8kΩ

2mA

v1 v2

Figure 2.1.

The nodal equations for the above system can be written as,

v1 − 6

2+

v1

4+

v1 − v2

4= 0 (2.1)

v1 − v2

4+

v2

8− 2 = 0 (2.2)

These equations can be converted into [Y ][V ] = [I] format where V is a columnvector [v1 v2]

T . The following Matlab code segment can be used to computenumerical values for the column vector.

9

Page 25: Matlab

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 asshown 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 thecircuit. The circuit equations can be written by treating the dependent sourcesas independent sources and later substituting the control parameter. Then thefinal set of equations can be formulated as a multiplication of matrices in thegeneral form [A][B] = [C] which could then be solved using Matlab. The sameprocedure is applied to Mesh analysis as well. However in this case the matrixequation 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 equationsas usual and then use Matlab to solve for the unknown variables. If the circuitcontains only dependent sources then a test voltage of 1V (or 1A current sourceas the case maybe) should be applied across the terminals where the Theveninresistance is computed. If the circuit contains both dependent and independentsources one can use the identity Rth = voc/isc to compute the equivalentresistance.

Example 3 Determine Rth at the terminals AB for the network shown inFig. 2.2.

−+2000Ix

2kΩ

1kΩ

Ix

3kΩ

2kΩ 1mA

A

B

V1 V2

Figure 2.2.

Since there are only dependent sources we apply a 1mA current source acrossthe terminals A-B. If the terminal voltage V2 is computed, Rth = V2/1E − 3will provide the Thevenin resistance. The nodal equations for the circuit are

Page 26: Matlab

Signal Processing Using Matlab 11

given by,

V1 − 2000Ix

2k+

V1

1k+

V1 − V2

3k= 0

V2 − V1

3k+

V2

2k= 1E − 3

Ix =V1

1k

The following code will compute Rth.

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 mVV = inv(Y)*I;Rth = V(2)/1E-3;% The answer is 1.3kOhms

In the above examples Matlab matrix manipulations are used to computeunknown circuit variables. In the next example we will see how Matlab can beused in a design situation to obtain circuit parameters.

Example 4 (Maximum Power Transfer Theorem) A 10V DC powersource has an internal resistance of 100Ω. Design the load resistor RL suchthat 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 associatedresistor can be chosen as RL.

2. TRANSIENT ANALYSISIn 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

Page 27: Matlab

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 circuitequations and plotting the time domain response of a circuit after a suddenchange in the network due to switches opening or closing. There are severalmethods available for transient analysis via Matlab.

(1) If the equation of the transient is known, Matlab can be used to plot thewaveform. In order to do this a time vector can be defined using [Start:

Step: Stop] and use matrix manipulations on the equation to find thevalues of the function at these time instances.

(2) If the equation is not known but the differential form is known together witha set of initial conditions, Matlab can be used to obtain the time responseusing the ode23 function.

(3) If the differential form is not known, replace the circuit elements with theirLaplace equivalents and obtain the transfer function at the output variableof interest. This can then be used together with the impulse function inMatlab to arrive at the output response.

(4) If the input waveform type is known (for example a step input) we canobtain the transfer function from the input to the output which can then besimulated via the lsim function in Matlab.

We will investigate the application of some of the methods available for transientanalysis using several examples in the sections that follow.

2.1. DIFFERENTIAL EQUATION REPRESENTATIONOF CIRCUITS

Ordinary differential equations (ODE) often involve a number of dependentvariables, as well as derivatives of order higher than one. To use the Matlab ODEsolvers, you must rewrite such equations as an equivalent system of first-orderdifferential equations. i.e. an equation of the form

dx(t)

dt= f(t, x).

Any ODE can be written in the form

dnx(t)

dtn= f(t, x,

dx(t)

dt, . . . ,

dn−1x(t)

dtn−1).

Then the above equation can be written as a system of first order equations bymaking the substitutions

x1 = x, x2 =dx

dt, . . . , xn =

dn−1x

dtn−1.

Page 28: Matlab

Signal Processing Using Matlab 13

The result is an equivalent system of n first order ODE’s of the form

dx1

dt= x2

dx2

dt= x3

...

dxn

dt= f(t, x1, x2, . . . , xn)

Once you represent the equation as a system of first order ODE’s, you can codeit as a function that the MATLAB ODE solver can use. The function should beof the form dxdt = odefunction(t,x). The following example illustratesthis procedure.

A first-order transient circuit with one storage element can be representedby 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. Thedifferential definition function for this case is

function [dx] = odefunc(t,x)% help instructions if necessarydx = 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) asx=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

d2x(t)

dt2+ a1

dx(t)

dt+ a2x(t) = f(t)

We choose variables x1 and x2 such that (note that these are function in time)

x1 = x anddx1

dt= x2

Thendx2

dt= −ax2 − bx1 + f(t)

Page 29: Matlab

14 MATLAB FOR ENGINEERS

If we assume y = [x1(t) x2(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 vectordy(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 orderODE 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 acolumn vector. Hence we use the zeros function in Matlab to ensure its correctdimensions.

2.2. LAPLACE TRANSFORM METHODS FORTRANSIENT ANALYSIS

The response of a system to initial conditions can also be found using theLaplace transform representation of the circuit. In some cases this is also knownas the network function of the circuit. For example if the input output equationis represented by

andny

dtn+ an−1

dn−1y

dtn−1+ . . . + a0y = bm

dmy

dtm+ bm−1

dm−1y

dtm−1+ . . . + b0y,

where x(t) is the input and y(t) is the output, the network function can berepresented by

H(s) =Y (s)

X(s)=

bmsm + bm−1sm−1 + · · · + b0

ansn + an−1sn−1 + · · · + a0.

The above expression can be entered into Matlab as a numerator and denomi-nator polynomials given by

num = [an an−1 . . . a0] and den = [bm bm−1 . . . b0].

Note that the coefficients should be arranged in descending powers of s. Theprocedure for simulating the transient response using the Laplace method is asfollows. The initial conditions are found after the circuit state changes whenthe switch is closed. Then replace the circuit elements with their correspondingLaplace equivalents and then obtain the transfer function as a rational polyno-mial as shown above. One can use the function lsim in Matlab to simulatethe transient response. In what follows we provide several examples whichillustrate these modeling procedures.

Page 30: Matlab

Signal Processing Using Matlab 15

2.3. TRANSIENT ANALYSIS EXAMPLESThe simplest form of analyzing a transient circuit is to define a time vector

via [Start: Step: Stop] and then compute the values of the transienttime domain equation explicitly via matrix manipulations.

Example 5 Assuming Vs = 10V DC source, C = 1µF and R = 100kΩ,use Matlab to plot the transient voltage across the capacitor.

−+Vs

R

C

Vo(t)

+

Figure 2.3.

In the absence of additional information we can assume that the capacitor isinitially unchanged. Then the output voltage Vo(t) changes according to,

Vo(t) = Vs(1 − e−1

RCt)

Direct MethodOne can directly simulate the final equation for Vo(t) using the following codesegment.

C = 1e-6;R = 100e3;Vs = 10;% Then the time constant in ms istau = R*C;% The plot for 1 s with 0.02s intervalst = 0:0.02:1;Vo = Vs*(1-exp(-t/tau));plot(t,Vo)gridtitle(’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

Page 31: Matlab

16 MATLAB FOR ENGINEERS

0 0.2 0.4 0.6 0.8 10

1

2

3

4

5

6

7

8

9

10Charging of a Capacitor

Time (s)

Vo(

t) (

Vol

ts)

Figure 2.4. Vo(t) - across the capacitor

The ODE governing the circuit in Figure 2.3 is

dvC

dt+

vC

RC=

VS

RC

The following code segment can be used to simulate the ODE. The followingcode is saved in a separate file named diff1.m.

function [dy] = diff1(t,y)% Help statement is necessaryR = 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 followingcode 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.

Page 32: Matlab

Signal Processing Using Matlab 17

Laplace MethodThe circuit in Figure ?? can also be simulated via a Laplace transformed circuit.The DC voltage source is replaced with a step function and the circuit is replacedby its corresponding transfer function. The transfer function is given by,

Vo(s)

Vs(s)=

1

1 + RCs.

However if we take Vs(s) = 10/s the system output is then given by theimpulse response of the circuit. The following matlab code segment can beused 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 stepimpulse(sys)

Another way of simulating the system is to assume the input signal form anduse the lsim function in Matlab to explicitly compute the output state. Forexample Vs(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 lengthlsim(sys,U,T); % will simulate the output state.

Example 6 For the transient circuit shown in Fig. 2.5, the initial currentflowing through the inductor is zero. At t = 0 the switch is moved from a tob, where it remains for 1 second. After which it is moved from b to c where itremains indefinitely. Plot the current flow through the inductor with respect totime.

Direct MethodFor the time duration 0 < t < 1 sec, the equations that governs the currentthrough the inductor is given by,

i(t) = 0.4(1 − e− t

τ1 ), where τ1 =200

50 + 50= 2s. (2.3)

Page 33: Matlab

18 MATLAB FOR ENGINEERS

−+40V

50Ω

150Ω

200H

50Ω

t = 0ab

c

Figure 2.5.

At t = 1 the current in the circuit will act as the initial value I0 for t > 1.

i(t = 1) = 0.4(1 − e−0.5) = I0

The circuit equation that governs the transient at t > 1 is given by,

i(t) = I0e− 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 examplet1 = 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); holdplot(t2,i2)gridtitle(’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 circuitsshown in Figure 2.6 From the Laplace equivalent circuit for 0 ≤ t < 1 thecurrent is

I(s) =0.2

s2 + 0.5s

We can explicitly simulate this equation using the impulse function. Thet = 1 value of the current will act as the initial condition I0 for the Laplace

Page 34: Matlab

Signal Processing Using Matlab 19

0 1 2 3 4 5 60

0.02

0.04

0.06

0.08

0.1

0.12

0.14

0.16RL Transient circuit

Time Sec

Indu

ctor

Cur

rent

(A

)

Figure 2.6. RL Transient

−+40

s

50 200s

50

(a) Circuit for 0 ≤ t < 0

150

200s−+

sI0

50

(b) Circuit for t ≥ 0

circuit for t ≥ 1. 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.

Page 35: Matlab

20 MATLAB FOR ENGINEERS

% The simulation for system sys1 for 0<= t < 1sys1 = 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>= 1sys2 = tf([I0 0],[200 200]);[Y2,T2] = impulse(sys2,[1:0.1:6]);plot(T1,Y1,T2,Y2)

Example 7 Plot vo(t) for t > 0 in the circuit given below including the timeinterval just prior to opening the switch.

−+12V 6kΩ

6kΩ

6kΩ

100µF

.t = 0

vo(t)

+

Figure 2.7.

Direct MethodFor the interval just prior to opening the switch, the capacitor is an open circuitand vo(t = 0−) = 12 · 6/(6 + 6). The capacitor initial value is 6V . Howeverwhen the switch opens, the output voltage drops to vo(t = 0+) = −6 · 6/(6 +6) = −3V . The capacitor will discharge through an equivalent resistance of4kΩ. The output for t > 0 is given by,

vo(t) = −3e−t

0.4

% for the time just prior to the opening of the switcht1=-0.5:0.1:0v1 = 6*ones(1,6);% for t > 0t2 = 0:0.01:2;

Page 36: Matlab

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 MethodThe differential equation that governs the circuit behavior for t > 0 is given by,

dvo

dt= −5

2vo (2.5)

The above equation has an initial condition given by, vo(t = 0+) = −3V. Thefollowing matlab code can be used to generate the transient response at theoutput. The differential definition is given by,

% The differential function used in the code has to be saved% in a separate file called diff1.mfunction 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)

Page 37: Matlab

22 MATLAB FOR ENGINEERS

The plot of the output signal for the time interval just before the switch is closedwill be the same as given in the previous case.

Example 8 Find the transient output vo(t) for t > 0 i the circuit given below.

−+12e−4tV

1Ω t = 0 500mH

vo(t)

+

Figure 2.9.

In this example it can be seen that the input signal is not a DC source with afixed value input. However the analysis methods available can still be used tofind the transient output. The time domain equation for the output is

vo(t) = 24(e−6t − e−4t). (2.6)

The differential equation that governs the output voltage is found to be,

dvo

dt+ 6vo = −48e−4t (2.7)

The Laplace representation of the output voltage is given by,

Vo(s) =−48

s2 + 10s + 24. (2.8)

The code below shows how to solve for the output using the three differentmethods we have leant so far. The Fig. 2.10 shows the output plot from thesimulations.

% 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

Page 38: Matlab

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 simulatinsys = tf([-48],[1 10 24]);impulse(sys)

The simulations result in an output voltage shown in Figure 2.10.

Time (sec)

Am

plitu

de

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 MethodThe time domain equation for vo(t) is given by,

vo(t) = 13.5e−2t − 9e−4t. (2.9)

Since the expression for the vo(t) is known we can simply simulate the transientwaveform 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)’)

Page 39: Matlab

24 MATLAB FOR ENGINEERS

−+12V

t = 0

12H

− vo +

14F

−+ 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 20

1

2

3

4

5

6

time (sec)

v o(t)

(V)

Transient output across 3Ω

Figure 2.12.

ODE Method

Page 40: Matlab

Signal Processing Using Matlab 25

If the current in the circuit is i(t) after the switch is closed the ODE that governsthe circuit response is given by

d2i

dt2+ 6

di

dt+ 8i = 0, with i(t = 0+) = 1.5 and vC(t = 0+) = 0. (2.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,x)dx = zeros(2,1); % This will ensure that dx is a column vectordx(1) = x(2);dx(2) = -8*x(1)-6*x(2);

The two initial conditions are x1(t = 0+) = i((t = 0+) and x2(t = 0+) =didt|t=0+ . TO find the initial condition for x2 we turn back to the original equation

vL + vR + vC = 6

Substituting the initial conditions we find

di

dt

t=0+

=6 − vC(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 byplot(t,3*y(:,1))

2.4. DESIGN EXAMPLESExample 10 A simple RLC circuit can be used to model an automobile ig-nition system1. Consider the RLC circuit given in Figure ??. The inductor isthe ignition coil which is magnetically coupled to the starter (the starter is notshown 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 isconnected to the series RLC circuit. To start the motor the battery is removedvia the switch at t = 0, thereby discharging the capacitor through the inductor.

Page 41: Matlab

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 beover damped. Do the following.

(1) Show that the RLC circuit in Figure ?? can be characterized by two firstorder differential equations. Also show that these two differential equationscan be reduced to an integrator-differential equation of the form,

dy(t)

dt+ ay(t) + b

∫ t

0y(τ)dτ = x(t)

Also show that this equation can be reduced to a second order differentialequation.

(2) Find The systems characteristic equation and determine the roots in termsof R, L and C.

(3) When the switch is turned on at t = 0 design for the value of the capacitorC such that the current i(t) reaches 1 A within 100 ms after switching andremains above 1 A for a time between 1 and 1.5 s. Obtain the design valuesmanually and also via Matlab using the following methods.

(4) Verify using Matlab that the system is over damped by finding the dampingratio and the natural frequency. (Hint : use roots or damp)

We have to take into account the physical status of the starter motor operationand how it effects our analysis. Before the switch is closed the capacitor chargesup with a current in the clockwise direction in the circuit. However when theswitch is flipped the current in the circuit is reversed when it discharges throughthe starter coil. We need to account for this sign change in some manner. Thiswill be discussed as the we proceed. First we note that the equation of thecircuit after the switch is closed is

vc + vL + vR = 0 (2.11)

1Basic Engineering Circuit Analysis: J. David Irwin and Chwan-Hwa Wu.

Page 42: Matlab

Signal Processing Using Matlab 27

We have assumed that the capacitor voltage is taking its direction from thecircuit after the switch is closed so we can conveniently assume that the initialvoltage for the capacitor is vC(t = 0+) = −12 rather than the positive valuebefore the switch is closed.

We use (??) to obtain the following:

vc + Ldi

dt+ iR = 0 (2.12)

di

dt= −i

R

L− vC

L, (2.13)

and we also note that,dvC

dt=

i

C. (2.14)

These two first order differential equations will characterize the circuit in Fig-ure. ??. If we substitute for vC from (??) in (??) we get the integro-differentialequation

Ldi

dt+

1

C

idt + iR = 0 (2.15)

Differentiating (??) and getting the Laplace transform we get the followingcharacteristic equation.

s2 +R

Ls +

1

LC= 0 (2.16)

Since it is given that the system is over-damped we should have two real andunequal roots. Lets call them s1 and s2. Then we have the following.

(s + s1)(s + s2) = s2 + (s1 + s2)s + s1s2 = s2 +R

Ls +

1

LC

From which we can deduce that;

s1 + s2 =R

L= 20

s1s2 =1

LC

We now have to choose arbitrary values for s1 and s2 and draw the currentwaveform to see if the design specifications are satisfied. For example if weuse the differential equation method to draw the current waveform we have touse the equations (??) and (??) to write the differential equation definition inmatlab as follows. let y ≡ [vc, iL] be our state vector.

function dy = diff1(t,y)dy = zeros(2,1) % This statement makes sure a vector is returned for dy

Page 43: Matlab

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 forcritical damping.

−+Vs(t)

C

6H 1F 1Ω

−vo(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 circuitor also known as the transfer function of the system.

Vo(s)

VS(s)=

6Cs2

(6C + 6)s2 + 6s + 1. (2.17)

The roots of the denominator polynomial will determine the damping of thesystem. Hence we carry out the design by changing the values of the capacitorC until the system system damping ration ζ = 1. We use the following Matlabprogram 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]);

Page 44: Matlab

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 forCl=0.1, Ch = 0.9 and step = 0.1. The corresponding output graphs aregiven in Figure ??.

It can be seen that the Critically damped poles occur at s = −0.33,−0.33and the corresponding capacitor value is C = 0.5F .

We now proceed to do the same computation manually in order to illustratethe procedure. The characteristic polynomial for the given system can be writtenas

s2 + 2ζω0s + ω20 ≡ s2 +

1

C + 1s +

1

6C + 6.

From which we deduce

ω0 =

1

6C + 6and ζ =

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 constantfrequency and secondly when the circuit is driven by a variable frequencysource. 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 ANALYSISIn this section we discuss the steady-state forced response of networks with

sinusoidal driving functions. In Matlab the angles are assumed to be in radiansunless otherwise mentioned. For example if we wish to plot the waveform givenby v(t) = 10 cos(ωt + 450) 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

Page 45: Matlab

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.10.1 0.20.2 0.30.3 0.40.4 0.50.5

0.6

0.6

0.7

0.7

0.8

0.8

0.9

0.9

Real

Imag

inar

y

(a) Poles of the System

1 2 3 4 5 6 7 8 90.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));

Page 46: Matlab

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 ω isthe frequency of operation. The real part and the complex part of a complexnumber can be found using real() and imag() functions. The angle or theargument of a complex number can be found using the function angle() andthe value returned is in radians. The steady state AC analysis is similar to theDC analysis carried out in a previous sections using nodal and loop analysisetc. In this case the matrices contain complex numbers as opposed to the realnumbers. The following example illustrates an analysis of a simple circuit withe sinusoidal driving function.

Example 12 Determine the Io in the network given in the figure using nodaland loop analysis.

j1Ω−+

6 6 00V

2 6 00 1Ω

Io

−j1Ω

V1 V2

Figure 2.16.

The two equations for the nodal analysis are,

V1

1 + j+

V2

1+

V2

1 − j= 2 6 00

V1 −V2 = −6 6 00

and Io = 1 · V2. The following Matlab code will compute Io. Again, similarto previous cases we convert the set of linearly independent equations into itsmatrix form.

% Let v = [v_1 v_2] then the equations in matrix form will beY = [1/(1+i) (2-i)/(1-i); 1 -1];I = [2 -6]’;v = inv(Y)*I;Io = 1*v(2);% The answer in Amperes isIo = 2.5000 - 1.5000i

If loop analysis is used to solve for Io, we have the following equations. let uschoose the loop currents as follows. The left most loop with I1, the right most

Page 47: Matlab

32 MATLAB FOR ENGINEERS

loop with I3 and the outer most loop with I2. Then the loop equations are,

I1 = −2 6 00

1(I1 + I2) + j1((I1 + I2) + 1(I2 + I3) − j1(I2 + I3) = 6 6 00

1I3 + 1(I2 + I3) − j1(I2 + I3) = 0

Then Io = −I3. 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 asIo = 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 Io is flowing. The analysistakes a similar path. For example if the source had a phase shift of the form V =6 6 450, 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 theconversion. All methods described in the DC analysis section is applicable forthe AC steady state analysis too.

4. VARIABLE FREQUENCY NETWORKPERFORMANCE

In the previous section analysis was limited to a fixed frequency at steadystate. In this section we will examine the performance of electrical networkswhen excited from variable-frequency sources. In particular we will discussmethods of obtaining Bode Plots via Matlab simulations. The first step towardsimulating a frequency response of a system is to obtain the network function orthe transfer function of the circuit at hand. Since in electrical circuits the inputsand outputs can be either currents or voltages there are several possibilitiesfor these transfer functions. The transfer function is obtained by substitutings = jω where ω is the variable frequency and s the Laplace variable to arriveat a ratio of two polynomials in s. For example, the transfer function G(s) forthe circuit given in Fig. ?? is given by,

Vo(s)

Vin(s)=

1

LCs2 + RCs + 1.

There are some matlab functions which simplify polynomial manipulationsused in frequency response analysis. conv(A,B) will give the convolution of

Page 48: Matlab

Signal Processing Using Matlab 33

Vin(s)

R L

C−Vo(s)

+

Figure 2.17. Series Resonant Circuit

the polynomials A and B. For example (s + 1) × (s + 2) = s2 + 3s + 2 canbe 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 thecommand roots(). Using the same example above, roots([1 3 2]) willresult 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 viathe function residue.

Example 13 Draw the bode plot for the network function

H(jω) =jω

(jω + 1)(0.1jω + 1)

substituting s = jω and multiplying the factors in the denominator (conv([11],[0.1 1]) we obtain the numerator num = [1 0] and the denominatorden = [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 toobtain most of the parameters from the frequency response once the sys =

tf(num,den); command is issued and the system is available in the matlabworkspace (read help file). Using bode with arguments will return the magni-tude, phase and frequency information rather than provide an output plot. Thebode plot can also be drawn using semilogx command. The magnitude of acomplex number can be found by using the abs function which will give youthe absolute value of the argument.

Page 49: Matlab

34 MATLAB FOR ENGINEERS

Frequency (rad/sec)

Pha

se (

deg)

; Mag

nitu

de (

dB)

Bode Diagrams

−40

−35

−30

−25

−20

−15

−10

−5

0From: U(1)

10−2

10−1

100

101

102

−100

−50

0

50

100

To:

Y(1

)

Figure 2.18. Bode plot

4.1. DESIGN EXAMPLESExample 14 The series RLC circuit in Fig. ?? is driven by a variable fre-quency source. If the resonant frequency of the network is selected as ω0 = 1600rad/s, find the values of C .

−+24 cos (ωt + 300)V

10mHi(t)

−vo(t)

+

C

Figure 2.19. Series resonant circuit

This example is a design oriented problem as opposed to the regular bodediagram. The frequency domain Transfer function of the network is given by,

H(jω) =Vo(jω)

Vin(jω)=

jω RL

(jω)2 + jω RL

+ 1LC

.

Since the resonant frequency is given we plot the above transfer function aroundthe given frequency with different values of C in order to find the value of C

Page 50: Matlab

Signal Processing Using Matlab 35

that gives ω0 = 1600 rad/s. This is accomplished by creating a matlab functionwith 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/sw = 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 drawnon the same figure window issue the command hold after the first plot com-mand. the figure below illustrates the transfer function response for severalvalues 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)

Am

plitu

de (

dB)

39µ F

35µ F

Figure 2.20.

Page 51: Matlab

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. ?? todesign a simple notch filter to eliminate the 60-Hz interference using Matlab.

+

vin

L

CReq

+

vo(t)

Figure 2.21. Telephone transmission line

We use the Laplace circuit of Fig ?? to analyze the problem. The voltagetransfer function of the telephone transmission system is given by,

Vo(s)

Vin(s)=

Req

Req +(L/C)

sL + (1/sC)

which can be rewritten as

Vo(s)

Vin(s)=

s2 +1

LC

s2 +s

ReqC+

1

LC

To design a notch filter that can eliminate the 60-Hz signal we have to lookat the bode plot of the system for some value of Req, L and C . We use thefollowing 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,:)’)

Page 52: Matlab

Signal Processing Using Matlab 37

gridxlabel(’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-

102

103

104

0

0.2

0.4

0.6

0.8

1

Frequency

Gai

n

Notch filter for R=100Ohm, L=50mH and C=100MicroF

Figure 2.22. Notch filter response

quencies in radians/sec. Hence the filter frequency for these component valuesis given by 420/(2π) = 66.8−Hz. Now we can repeatedly change the valuesof Req, L and C till we obtain the correct notch frequency at 60-Hz. The designvalues for the filter will be R = 100, L = 70mH and C = 100µF . The filterresponse these values is given in Fig. ??.

102

103

104

0

0.2

0.4

0.6

0.8

1

Frequency

Gai

n

Notch filter for R=100Ohm, L=70mH and C=100MicroF

Figure 2.23. Notch filter response for 60-Hz

We could have automated the design process used above by using the followingprogram sequence.

function [magnitude,phase,frequency] = notch60a(R,Ll,Lh,Cl,Ch,n)% [magnitude,phase,frequency] = notch60a(R,Ll,Lh,Cl,Ch,n)

Page 53: Matlab

38 MATLAB FOR ENGINEERS

% L1 <= L < Lh and Cl <= C <= Ch are the limits of change% n gives us the number of stepsLstep = (Lh-Ll)/n;Cstep = (Ch-Cl)/n;flag = 0;for i = 0:n-1

for j = 0:n-1L = 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,:)’)gridxlabel(’Frequency’)ylabel(’Gain’)title(’60-Hz Notch filter’)flag = 1;break

endendif flag==1

breakend

end

In this program we supply a range for both L and C and the number of stepsto sweep these values. Then the two for loops will increment the componentvalues for n steps till the conditions of the if loop is satisfied. If it is satisfiedthen the program loops are exited using the break function of Matlab. Forconvenience 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 frequenciesand look at the transient output for confirmation. Hence to demonstrate theeffectiveness of the filter we choose the input voltage,

vin(t) = 1 sin[(2π)60t] + 0.2 sin[(2π)1000t]

Page 54: Matlab

Signal Processing Using Matlab 39

Which has a 60-Hz and 1-KHz signal added together. We use the followingMatlab 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 vectorVin = 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]); gridsubplot(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 smallvalue by the notch filter.

5. FOURIER ANALYSISFourier 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 theresponse of a linear time invariant system to a single sinusoidal signal is easilycalculated, it is now equally easy, with the aid of super-position, to find thesystem response to a sum of sinusoidal inputs.

5.1. FUNDAMENTALS OF FOURIER ANALYSISA continuous-time signal is periodic if

f(t) = f(t ± T0) for all t

where the period is the smallest value of T0 that satisfies this equation. TheFourier series comes in two different forms, Trigonometric and the ExponentialFourier series.

Page 55: Matlab

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)

Am

plitu

deV

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)

Am

plitu

de

Vout

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) = a0 +∞∑

n=1

(an cos nω0t + bn sinnω0t) (2.18)

where,

a0 =1

T0

∫ t1+T0

t1

f(t) dt, an =2

T0

∫ t1+T0

t1

f(t) cos nω0t dt, and

bn =2

T0

∫ t1+T0

t1

f(t) sinnω0t dt, with ω0 =2π

T0.

Exponential Fourier Series : For a periodic function f(t) the exponentialFourier series is given by,

f(t) =∞∑

n=−∞

cnejnω0t

where,

cn =1

T0

∫ t1+T0

t1

f(t)e−jnω0tdt and T0 =2π

ω0.

Page 56: Matlab

Signal Processing Using Matlab 41

The exponential Fourier series can be derived from the trigonometric seriesin the following manner. We first note the following identities;

cos θ =ejθ + e−jθ

2and sin θ =

ejθ − e−jθ

2j

Substituting the above in (??) we derive the exponential Fourier series as fol-lows,

f(t) = a0 +

∞∑

n=1

[

an

2(ejnω0t + e−jnω0t) − jbn

2(ejnω0t − e−jnω0t)

]

= a0 +

∞∑

n=1

[(

an − jbn

2

)

ejnω0t +

(

an + jbn

2

)

e−jnω0t

]

= c0 +∞∑

n=1

(cnejnω0t + c−ne−jnω0t) (2.19)

Where,

c0 = a0, cn =an − jbn

2, and c−n =

an + jbn

2for n = 1, 2, . . . .

The coefficient c−n is the complex conjugate of cn. Note that,

|cn| =

a2n + b2

n

2= |c−n|.

It follows that the exponential Fourier series given in (??) can be written as,

f(t) =

∞∑

n=−∞

cnejnω0t (2.20)

where,

cn =1

T0

∫ t1+T0

t1

f(t)e−jnω0tdt (2.21)

5.2. SPECTRUM OF A PERIODIC WAVEFORMThe frequency spectrum is the plot of the amplitudes of the harmonics versus

frequency. The phase spectrum is the plot of the phase of harmonics versusthe frequency. The expressions for the spectrum can be derived by equatingthe expressions obtained for the exponential and trigonometric Fourier series.Note that the spectrum comes in two forms. The one-sided spectrum derivedvia the trigonometric Fourier series and the two-sided spectrum derived from

Page 57: Matlab

42 MATLAB FOR ENGINEERS

the exponential Fourier series. The spectrum of f(t) can be obtained in thefollowing manner. The expression given in (??) can be reduced to,

f(t) = a0+∞∑

n=1

a2n + b2

n cos (nω0t + φn) = c0 +∞∑

n=1

2|cn| cos (nω0t + φn)

where φn = tan−1(

− bn

an

)

. Here n = 1, 2, . . .. Then the single-sided spectrum

is given by,a0 = c0,

a2n + b2

n = 2|cn|, φn for n > 0

The double sided spectrum is given by,

a0 = c0, |cn|, φn for n 6= 0.

In general for real f(t) we have |cn| having even symmetry and φn havingodd symmetry. In some cases the Fourier coefficients are substituted withDn = 2cn. From the above discussion it can be seen that if cn from (??) isknown the spectrum of the periodic signal can be drawn. The Matlab functiontrapz can be used to compute the integration in (??) to arrive at the coefficients.

5.3. STEADY STATE NETWORK RESPONSE TOPERIODIC INPUTS

The Fourier series can be used to analyze the steady state response of linearsystems to periodic inputs. Let us assume that a passive network has an impulseresponse of h(t) and is fed with a signal f(t) and the corresponding output signalfrom the network to be g(t). Then using convolution,

g(t) = h(t) ∗ f(t)

=

∫ ∞

τ=0h(τ)f(t − τ)dτ

=

∫ ∞

τ=0h(τ)

∞∑

n=−∞

cnejnω0(t−τ)dτ

=∞

n=−∞

cnejnω0t

∫ ∞

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

=

∞∑

n=−∞

cnejnω0tH(jnω0t) =

∞∑

n=−∞

dnejnω0t

where dn = H(jnω0)cn and H(jnω0) =∫ ∞

τ=0 h(τ)e−jnω0τ . Hence it can beclearly seen that the output is also periodic with period T0 and the Fourier seriesat the output is simply the Fourier coefficients at the input multiplied by thenetwork function.

Page 58: Matlab

Signal Processing Using Matlab 43

Example 16 Find the exponential Fourier series of the signal given in fig.(??).

T0 2T0

t

v(t)

V

Figure 2.25. Input Signal

Note that the waveform can be defined as,

v(t) =V

T0t, for 0 ≤ t ≤ T0

Then by definition, the Fourier coefficients of an exponential series can becomputed as,

cn =1

T0

∫ T0

0v(t)e−jnω0tdt =

1

T0

∫ T0

0

V

T0te−jnω0tdt. (2.22)

Note that the integral is evaluated for one time period T0. i.e. t1 = 0 for thiscase.

cn =V

T 20

∫ T0

0td

dt

[

e−jnω0t

−jnω0

]

dt (2.23)

The above expression is valid for n 6= 0 as n appears in the denominator. Forsuch a case c0 has to be computed separately. Using integration by parts onecan arrive at,

cn =V

T 20

(

1

−jnω0

)[

( te−jnω0t∣

T0

0+

∫ T0

0e−jnω0tdt

]

=jV

2πn. (2.24)

Also,

c0 =1

T0

∫ T0

0

V

T0t dt =

V

2. (2.25)

Page 59: Matlab

44 MATLAB FOR ENGINEERS

The Fourier representation of the waveform in (??) is then given by,

v(t) =V

2+

∞∑

n=−∞n6=0

jV

2πnejnω0t. (2.26)

We can use the following Matlab code segment to plot the Fourier waveformgiven by the above equation. For example Figure ?? gives the approximationsfor n = 2 and n = 100. It can be seen that higher the number of terms thebetter the approximation is. We have assumed that T0 = 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~=0m(k,:) = (i*10/(2*pi*N))*exp(i*N*w*t);k = k+1;

endendm = sum(m)+10/2;

0 0.5 1 1.5 20

2

4

6

8

10n=2

time (sec)0 0.5 1 1.5 2

0

5

10

15n=100

time (sec)

Figure 2.26. Fourier Approximation of a Saw-tooth Waveform

Substituting values for n, the spectrum can be identified as

c0 =V

26 0, c1 =

V

2π6

π

2, and c−1 =

V

2π6 −π

2

Page 60: Matlab

Signal Processing Using Matlab 45

The spectrum of this signal is given in Figure ??. Note the clear differences inthe one-sided and the two-sided spectrum. For the one-sided spectrum you areessentially drawing the coefficients and phase of,

f(t) = c0 +∞∑

n=1

2|cn| cos(nω0t + φn)

while for the two sided spectrum it is the magnitude and phase of,

f(t) = c0 +

∞∑

n=−∞n6=0

cnejnω0t.

c0

ω0 2ω0 3ω0

magnitude

ω

2c1

2c2

2c3

(a)

ω0 2ω0−ω0−2ω0

c0

c1

c2

c−1

c−2

magnitude

ω

(b)

phase

ω

π

2

ω0 2ω0 3ω0

(c)

ω0 2ω0

−ω0−2ω0

phase

ω

π

2

−π

2

(d)

Figure 2.27. Single- and Double- sided spectrum

The same spectrum can be obtained by using numerical integration via Matlabon (??).

function [mCn,pCn,n] = fou1spec(period,n,time_step)t = 0:time_step:period;

Page 61: Matlab

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;

endmCn=abs(c);pCn=180*angle(c)/pi;

The Amplitude and phase spectrum can be plotted using the following com-mands

% double sided amplitude spectrumsubplot(2,2,1); stem([-n:n],mCn)% double sided phase spectumsubplot(2,2,3); stem([-n:n],pCn)% single sided magnitude spectumsubplot(2,2,2); stem([0:n],[mCn(n+1) 2*mCn(n+2:2*n+1)])% single sided phase spectrumsubplot(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;

endF = 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 thatthe imaginary parts are ignored when plotting the function. In order to avoidthis replace F = sum(F); with F = real(sum(F));.

Page 62: Matlab

Signal Processing Using Matlab 47

−2 −1 0 1 20

1

2

3

4

5

6Double sided Spectrum

n

Mag

nitu

de

−2 −1 0 1 2−100

−50

0

50

100

n

Pha

se

0 0.5 1 1.5 20

1

2

3

4

5

6Single Sided Spectrum

n

Mag

nitu

de

0 0.5 1 1.5 20

20

40

60

80

100

n

Pha

se

Figure 2.28. Spectrum

If the waveform in (??) is now used as an input to the circuit given in Figure ?? wecan find the expression for vo(t) using the Fourier analysis technique. AssumeT0 = 0.5, V = 2, R = 1Ω and C = 1F . From the given values we can deduce

vi(t)

R

C vo(t)

Figure 2.29. RC Circuit

that c0 = 1 and ω0 = 4π. The transfer function for all the nω0 frequencies of

Page 63: Matlab

48 MATLAB FOR ENGINEERS

the circuit is given by,

H(jnω0) =vo(jnω0)

vi(jnω0)=

1/jnω0

1 + 1/jnω0=

1

1 + jnω0=

1√

1 + (nω0)26 − tan−1(nω0).

Previously we have shown from (??) that,

vo(t) = d0 +

∞∑

n=−∞n6=0

dnejnω0t

where dn = H(jnω0)cn. Therefore, d0 = H(jnω0)|n=0 · c0 = 1 6 0. and ateach n,

dn =

[

1√

1 + (nω0)26 − tan−1(nω0)

]

·(

j

)

(2.27)

Hence the output signal can now be written as,

vo(t) = 1 +∞∑

n=−∞n6=0

1

nπ√

1 + (nω0)2ej4πnt±π

2−tan−1(nω0). (2.28)

The output of the filter can be simulated via Matlab using the following codesegment

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;

endF = sum(F);mCn=abs(d);pCn=180*angle(d)/pi;

The plot of the output waveform is given in Figure ??.

Exercise 11 Follow the same procedure for the trigonometric Fourier series.

Page 64: Matlab

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)

Am

plitu

de

Figure 2.30. Input output plot for the RC filter

6. FOURIER TRANSFORMFourier 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ωtdt. (2.29)

F (ω) is a complex function of frequency. The inverse Fourier transform isgiven by

F−1[F (ω)] = f(t) =1

∫ ∞

−∞

F (ω)ejωtdt. (2.30)

Example 17 Find the Fourier transform of the function

f(x) =

1 for − 0.5 < x < 0.50 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)~=0m = 1*exp(-i*w(N)*t);M(N) = trapz(t,m);

elseM(N)=1;

endend

Exercise 12 Plot the Fourier transform of the sinusoidal signal x(t) =A cos ωat, −a/2 ≤ ta/2.

Page 65: Matlab

50 MATLAB FOR ENGINEERS

7. THE LAPLACE TRANSFORMThis section focus’s on obtaining Laplace transforms when the time domain

equation is given and the inverse Laplace transforms when the transfer functionis given. The first method of analysis is using the Symbolic math Toolbox frommatlab. The variables that are used in symbolic math have to be defined assymbolic using the sym or syms command. The frequently used command ofthe 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 shifttheorem 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) =s2 + 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 moreclearly. If one needs to simplify the equation or combine elements of a solutiongiven by matlab, you can use the simplify command.

Page 66: Matlab

Signal Processing Using Matlab 51

8. CONVOLUTION INTEGRAL VIA MATLABThe 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 2sduration 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 inFig. ??.

Example 21 Plot f(t) using the convolution function if,

F(s) =1

(s + 1)(s + 2).

We use the property F1(s)F2(s) ⇐⇒ f1(t) ∗ f2(t).

% \beginVerbatim[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

Page 67: Matlab

52 MATLAB FOR ENGINEERS

0 0.5 1 1.5 20

0.2

0.4

0.6

0.8

1

f1(t)

time (s)0 0.5 1 1.5 2

0

0.2

0.4

0.6

0.8

1

f2(t)

time (s)

0 0.5 1 1.5 2 2.5 3 3.5 40

20

40

60

80

100

f1(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 THEOREMSThe 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(s2 + 2s + 2)

Page 68: Matlab

Signal Processing Using Matlab 53

0 1 2 3 4 50

0.2

0.4

0.6

0.8

1

f1(t)

time (s)0 1 2 3 4 5

0

0.2

0.4

0.6

0.8

1

f2(t)

time (s)

0 1 2 3 4 5 6 7 8 9 100

5

10

15

20

25

30

f1(t)*f

2(t)

time (s)

Figure 2.32.

and the corresponding time function

f(t) = 5 + 5√

2e−t cos (t − 1350).

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

From the plot in Fig. ?? we can see that f(t = 0) = 0 and the steady state value(final value) is 5.

Page 69: Matlab
Page 70: Matlab

Chapter 3

TRIALS

state transition algorithm for each neuron j ∈ 0, 1, . . . ,M − 1

calculate the weighted sum Sj using Eq. (6);if (Sj > tj)

turn ON neuron; Y1 = +1else if (Sj < tj)

turn OFF neuron; Y1 = −1else

no change in neuron state; yj remains unchanged; .

55

Page 71: Matlab
Page 72: Matlab

Index

Graphics, 1 Numerically, 1

57