0% found this document useful (0 votes)
21 views70 pages

EEE - ECE382 - Modelling and Simulation Lab Manual - Spring 2025

The Laboratory Manual for EEE/ECE 382 at Brac University outlines the course objectives, which include familiarizing students with microprocessors and enabling them to design microcontroller-based systems. It details course outcomes, assessment methods, and safety guidelines for laboratory work, along with a list of experiments and necessary software requirements. The manual emphasizes the importance of safety in the lab and provides a structured approach to learning through practical experiments using MATLAB and Simulink.

Uploaded by

uchiha madara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views70 pages

EEE - ECE382 - Modelling and Simulation Lab Manual - Spring 2025

The Laboratory Manual for EEE/ECE 382 at Brac University outlines the course objectives, which include familiarizing students with microprocessors and enabling them to design microcontroller-based systems. It details course outcomes, assessment methods, and safety guidelines for laboratory work, along with a list of experiments and necessary software requirements. The manual emphasizes the importance of safety in the lab and provides a structured approach to learning through practical experiments using MATLAB and Simulink.

Uploaded by

uchiha madara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Laboratory Manual

Modeling and Simulation Laboratory


EEE/ECE 382 (V3)

Department of Electrical & Electronic Engineering (EEE)


School of Engineering (SoE)
Brac University

Revision: August 2022


A. Course Objectives:
The objectives of this course are to:
-​ familiarize students with the basic architecture of microprocessors and microcontrollers, and provide them
with a sound understanding of different peripheral modules, their operation mechanism, and interfacing with
external devices for various applications.
-​ enable the students to develop the ability to design and implement microcontroller-based embedded
systems using state-of-the-art software tools.

B. Course Outcomes, CO-PO-Taxonomy Domain & Level- Delivery-Assessment Tool:


Sl. CO Description POs Bloom’s Delivery Assessment
taxonomy methods and tools
domain/level activities
EEE_ECE 382 Modeling and Simulation
C Illustrate a linear system through a Cognitive/ Apply Lab Lecture, Assignment,
O differential equation, transfer function, Notes Lab Work, Lab
1 magnitude, impulse and step response Exam

C Apply the concept of state-space a Cognitive/ Apply Lab Lecture, Assignment,


O representation to model linear and Notes Lab Work, Lab
2 nonlinear systems Exam, Project

C Demonstrate the linearization of a Cognitive/ Create Lab Lecture, Assignment,


O nonlinear system models Notes Lab Work, Lab
3 Exam

C Develop a suitable model for a given e Cognitive/ Create Lab Lecture, Assignment,
O system, with proper reasoning of the Notes Project
4 selection of model type and order, and
compute the model error

C Identify and Use appropriate e Cognitive/ Apply Lab Class, Assignment,


O simulation tools to simulate a given Psychomotor/Mani Lectures, Lab Work, Lab
5 linear and non-linear system or model pulation Tutorial Exam, Project

C. Mark Distribution

Assessment Tools Weightage


ATTENDANCE & PERFORMANCE 10
Assignment 30
Lab Test (MID+FINAL) 30
Project (Simulation+Report) 30
D. References
Sl. Title Author(s) Publication Edition Publisher ISBN

1 Simulation of Harold Klee & 2011 2nd CRC Press 13: 978-14398
Dynamic Systems Randal Allen 36736
with MATLAB and
Simulink

2 Modeling and Charles M. Close, Dean 2012 3rd Lippincott 13: 978-81265
Analysis of Dynamic K. Frederick, Jonathan Williams & 39291
Systems C. Newel Wilkins

Lab Safety and Security Issues

1.​ Laboratory Safety Rules (General Guidelines):


The Department of EEE maintains general safety rules for laboratories. The guideline is attached in front of
the door in each of the laboratories. The written rules are as follows.

1.​ Closed shoes must be worn that will provide full coverage of the feet and appropriate personnel
clothing must be worn.
2.​ Always check if the power switch is off before plugging into the outlet. Also, turn the instrument or
equipment OFF before unplugging from the outlet.
3.​ Before supplying power to the circuit, the connections and layouts must be checked by the teacher.
4.​ Voltage equal to or above 50V is always dangerous. Therefore, extra precautions must be taken
when the voltage level is increased.
5.​ Extension cords should be used only when necessary and only on a temporary basis.
6.​ Once the lab exercise is done, all equipment must be powered down and all probes, cords, and
other instruments must be returned to their proper position.
7.​ In case of fire, disconnect the electrical mains power source if possible.
8.​ Students must be familiar with the locations and operations of safety and emergency equipment
like Emergency power off, Fire alarm switches, and so on.
9.​ Eating, drinking, chewing gum inside electrical laboratories are strictly prohibited.
10.​Do not use damaged cords or cords that become too hot or cords with exposed wiring and if
something like that is found, inform the teacher/LTO right away.
11.​ No laboratory equipment can be removed from their fixed places without the teacher/LTO’s
authorization.
12.​No lab work must be performed without the laboratory teacher/lab technical officer being present.

2. Electrical Safety:
To prevent electrical hazards, there are symbols in front of the Electrical Distribution Board, High voltage
three-phase lines in the lab, Backup generator, and substation. Symbols related to Arc Flash and Shock
Hazard, Danger: High Voltage, Authorized personnel Only, no smoking, etc. are posted in required places.
Only authorized personnel are allowed to open the distribution boxes.

3. Electrical Fire:
If an electrical fire occurs, try to disconnect the electrical power source, if possible. If the fire is small, you
are not in immediate danger, use any type of fire extinguisher except water to extinguish the fire. When in
doubt, push the Emergency Power Off button.

4. IMPORTANT:
Do not use water on an electrical fire.

List of Experiments

Exp. Experiment Name Tentative Is this


No. schedule experiment
used for any CO
assessment?

Yes No

00 Ice-breaking session: Introducing necessary 1st week


software, discussion on course outcomes,
assessment plan, group formation, etc.

01 Introduction to Modelling and Simulation, Principles 2nd week


of Modelling, MATLAB/Simulink as simulation tools ✔

02 Modelling of dynamic systems: Electrical systems, 3rd week


generation of system equations, Transfer functions, ✔
poles and zeroes. Circuit Simulation

03 State-space model: state variable formulation. 4th week


04 Linearization of nonlinear model: Linear system 5th week


Simulation. ✔

MID LAB QUIZ 6th week


MID SIMULATION TEST 7th week



Least square method: Determination of 8th week

5 polynomial using method of Least Square
Curve Fitting

Numerical methods for differential equations: Linear 9th week


6 system simulation ✔

Runge-Kutta Discretization: Numerical Method for 10th week


7 Differential equations. ✔

Introduction to system identifications using Matlab 11th week


8 ✔

FINAL LAB SIMULATION TEST and Project 12th week


Submission ✔

Created and Updated by:


1.​ Nahid Hossain Taz (Exp- 1,2,3,4,5,6,7)
2.​ Md. Mahmudul Islam (Exp-8)
3.​ Md. Mehedi Hasan Shawon (Exp- 04)
Experiment No. 0
Ice-breaking session: Introducing necessary software,
discussion on course outcomes, assessment plan, group
formation, etc.
During the lab session of the first week the following topics should be discussed:

●​ Introducing the course materials, course outcomes, marks distribution, and assessment plan
●​ Instructions regarding group formation
●​ Lab report submission guidelines
●​ Necessary software

1.​ Introducing the course materials, course outcomes, marks distribution, and assessment plan​
The list of experiments should be provided to the students, and also an overview of the topics can be
given. The course outcomes should be explained so that the students can have a clear understanding
of what they are expected to learn from this course. The complete marks distribution and the
assessment plan should be discussed as well.

2.​ Instructions regarding group formation​


The following instructions could be provided to the students for the group formation purpose:
a.​ Each group should have at most three members (as this is a simulation-based lab).
b.​ A group should be formed with the students having the same course code.
c.​ All group members of a group should belong to the same section (exceptions can be made
depending upon the situation).

3.​ Lab report submission guideline​


General guidelines for submitting the report could be as follows:
a.​ Each group will submit one report per experiment
b.​ The hard copy of the report should be submitted before the next lab session (a soft copy should
also be submitted on the online platform, if necessary).
c.​ All group members should contribute equally. If any member is not cooperating, you may remove
his/her name from the lab report and send an email to the instructor informing the issue.
d.​ Late submission will not be accepted.
e.​ Plagiarism will be treated harshly.
f.​ A cover page should be added with the report including the course code, course name, experiment
no., experiment name, name, and ID of each of the group members.
g.​ Comments should be used inside the code to make it understandable and a proper explanation of
the workings should be also provided. Also, necessary screenshots of the outputs for each of the
codes should be attached.
The report would be assessed in terms of comprehensiveness, cleanliness, and overall presentation.

4.​ Necessary software


●​ Software and Device requirement:

●​ MATLAB
●​ Simulink

Minimum PC specifications:
Windows/Mac: Microsoft® Windows® 7 Professional, Enterprise, Ultimate or Home Premium (64-bit);
Windows 8 (64-bit) (All Service Packs); Windows 10 (64-bit); Windows 2008 R2 Server; Windows 2012
Server (All Service Packs).
Ram: 2 GB
Processor: Intel® Pentium® 4 or AMD Athlon XP 2000 with multi-core CPU

●​ Display resolutions: 1,024 x 768 display resolution with true color (16-bit color)
Experiment No. 1

Familiarization with MATLAB and Simulink

1.​ Objective: This experiment is intended to familiarize the students with the basic simulation operations
of MATLAB and Simulink
2.​ Introduction:
MATLAB® is a programming platform designed specifically for engineers and scientists to analyze and
design systems and products that transform our world. The heart of MATLAB is the MATLAB language,
a matrix-based language allowing the most natural expression of computational mathematics. MATLAB
is a high-level programming language designed for engineers and scientists that expresses matrix and
array mathematics directly. You can use MATLAB for everything, from running simple interactive
commands to developing large-scale applications.
Simulink provides a graphical editor, customizable block libraries, and solvers for modeling and
simulating dynamic systems. It is integrated with MATLAB®, enabling you to incorporate MATLAB
algorithms into models and export simulation results to MATLAB for further analysis.

3.​ Software and Device requirement:

●​ MATLAB
●​ Simulink

Minimum PC specifications:
Windows/Mac: Microsoft® Windows® 7 Professional, Enterprise, Ultimate or Home Premium (64-bit);
Windows 8 (64-bit) (All Service Packs); Windows 10 (64-bit); Windows 2008 R2 Server; Windows 2012
Server (All Service Packs).
Ram: 2 GB
Processor: Intel® Pentium® 4 or AMD Athlon XP 2000 with multi-core CPU
Display resolutions: 1,024 x 768 display resolution with true color (16-bit color)
MATLAB Screen:

Figure: MATLAB 2019b

a.​ Built-in Functions:


●​ sin, cos, sqrt, abs, gcd, lcm, size, length, isempty, isequal,
magic, linspace
●​ To know more about the function, you can use help
●​ help sin
●​ You can also use doc for documentation
●​ doc sin
●​ clc clears all the text from the Command Window, resulting in a clear screen
●​ Close all clears all open MATLAB figure windows
●​ Clear all clears all data stored to a variable
b.​ Matrix Manipulation:
I.​
Scalar:​ s=5
Vector:​ a=[1 2 3];​ %row vector
​ b=[4;5;6];​ %column vector
​ c=1:5​​ %row vector
Matrix:​ ​ mat=[1 2 3; 4 5 6; 7 8 9]
% Use percent sign for comments
% Suppress output by adding a semicolon at the end of that command
Function Description

zeros(i,j) creates an i x j matrix of all zeros

ones(i,j) creates an i x j matrix of all ones

rand(i,j) creates an i x j matrix of random elements (between 0 and 1)

eye(i) creates an i x i identity matrix (a matrix of zeros with ones on the diagonal)

II. Vector Operations:


●​ a+3 % add a scalar to a vector
●​ a+b % element by element addition
●​ a-b % element by element subtraction
●​ a*3 % multiply a vector and a scalar
●​ a.*b % element by element multiplication
●​ a’ %transpose
Find Difference between:
a*b & a.*b
a/b & a./b
a^3 & a.^3

III. Matrix Indexing


Index starts from 1 (not from 0)
Column-major Convention
Here: A = [ 1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
●​ A(3,2) % The element of 3rd row and 2nd column
●​ A(:,1) % The 1st Column
●​ A(2, 2:3) %Through 2nd to 3rd elements of 2nd row
●​ sum(A(2,:)) % Sum all elements of 2nd row
●​ max(A(3,:)) %Maximum element of the 3rd row
Expression Description

5:10 Values 5 to 10.

10:-1:5 Values 10 to 5 (using decrement of 1)

A(1:2,3:4) Row 1 to 2, Column 3 to 4

A(:) Produces one long column, which is a concatenation of the individual columns.

A(5:8) Slicing from the concatenated columns. In this case, you are getting the values of the
second column.

A(end) end is a special value that indicates the end of the matrix. You could have also written
A(end, end) to specify the ending row and the ending column.

A(1:4,4) This gets the values of the last column (rows 1 to 4 and column 4). Since you are
specifying all rows and the final column, you could also use the notation: A(1:end, end)
or the colon operator on its own, which specifies the entire range of rows A(:, end)

IV. Complex Number


●​ i % Imaginary Unit
●​ j % Imaginary Unit
●​ sqrt(-1) % Imaginary Unit
●​ x = 3+4i % Complex Number
●​ y = complex(3,4) % Complex Number
●​ real (x) % Real part of x
●​ imag(x) % Imaginary part of x
●​ angle(x) % argument of x
●​ abs(x) % absolute value of x
●​ conj(x) % conjugate value of x
V. Math Expressions
●​ a=2, b=3, c=4, d=6
●​ x=a^2+b^3-3*(c+d)/6+9
●​ exp(x) %exponential
●​ log(x) %natural logarithm, inverse of exp(x)
●​ log10(x) %base 10 logarithm, inverse of 10^x
C. Plotting Figures

Graphing Functions MATLAB Command

Label the horizontal axis. xlabel('text')

Label the vertical axis. ylabel('text')

Attach a title to the plot. title('text')

Change the limits on the x and y axis. axis([xmin xmax ymin ymax])

Keep plotting in the same window. hold on

Turn off the hold off


"keep-plotting-in-the-same-window-command".

I.​ Basic Plotting:


●​ Plot-1
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
●​ Plot-2
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)
●​ Plot-3
Y = magic(4)
figure
plot(Y)

●​ Plot-4
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);

figure
plot(x,y1,x,y2,'--',x,y3,':')
●​ Plot-5
x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
figure
plot(x,y1,'g',x,y2,'b--o',x,y3,'c*')
●​ Plot-6
% Create data and 2-by-1 tiled chart layout
x = linspace(0,3);
y1 = sin(5*x);
y2 = sin(15*x);
tiledlayout(2,1)
% Top plot
ax1 = nexttile;
plot(ax1,x,y1)
title(ax1,'Top Plot')
ylabel(ax1,'sin(5x)')
% Bottom plot
ax2 = nexttile;
plot(ax2,x,y2)
title(ax2,'Bottom Plot')
ylabel(ax2,'sin(15x)')

●​ Plot-7
x = linspace(-pi,pi);
y1 = sin(x);
plot(x,y1)
hold on
y2 = cos(x);
plot(x,y2)
hold off
●​ Plot-8
subplot(2,2,1)
x = linspace(0,10);
y1 = sin(x);
plot(x,y1)
title('Subplot 1: sin(x)')

subplot(2,2,2)
y2 = sin(2*x);
plot(x,y2)
title('Subplot 2: sin(2x)')

subplot(2,2,3)
y3 = sin(4*x);
plot(x,y3)
title('Subplot 3: sin(4x)')

subplot(2,2,4)
y4 = sin(8*x);
plot(x,y4)
title('Subplot 4: sin(8x)')

For proper graph:


% Define parameters for figure
set(0, 'DefaultAxesFontName','cambria');
set(0, 'DefaultAxesFontSize',12);
set(0,'defaultlinelinewidth',2);
set(0,{'DefaultAxesXColor','DefaultAxesYColor','DefaultAxesZColor'},{'k','k','k'})
D. Control Flow Statement
For Loop
% Define a row vector
row_vector = [3, 7, 2, 9, 5, 8, 1];
% Initialize counter
num_elements = 0;
% Loop through the row vector
for i = 1:length(row_vector)
num_elements = num_elements + 1;
end
% Display the number of elements
fprintf('Number of elements in the row: %d\n', num_elements);

if-else if-else Condition


% Define a matrix
A = [3, 7, -2; 9, 5, 8; -1, 4, 0];
% Compute the sum of all elements
sumA = sum(A, 'all');
% Check conditions
if sumA > 20 && any(A(:) < 0)
disp('The sum is greater than 20, and the matrix contains negative
elements.');
elseif sumA <= 20 || all(A(:) > 0)
disp('The sum is 20 or less, or all elements are positive.');
else
disp('The matrix does not meet the above conditions.');
end
While Condition

% Initialize a random number


% Generates a random number between 1 and 100
num = randi([1, 100]);
count = 0;
% While loop to find a number greater than 90
while num <= 90
fprintf('Current number: %d (less than or equal to 90)\n', num);
num = randi([1, 100]); % Generate a new random number
count = count + 1;
end
% Display the final number and iterations taken
fprintf('Found a number greater than 90: %d\n', num);
fprintf('Total iterations: %d\n', count);

Switch-Case Condition
% Define a number
% Generates a random number between -10 and 10
num = randi([-10, 10]);
% Switch case to categorize the number
switch true
case (num > 0)
fprintf('The number %d is Positive.\n', num);
case (num < 0)
fprintf('The number %d is Negative.\n', num);
case (num == 0)
fprintf('The number is Zero.\n');
otherwise
fprintf('Unexpected value.\n');
end
E. Simulink
●​ Type Simulink in the command window or click on the Simulink icon
●​ Chose Blank Model from the window
●​ You will see the following window

Figure: Simulink
●​ Click Library Browser from the display panel.

Figure: Simulink Library Browser


●​ Choose Simscape> Electrical> Specialized Power Systems>
Fundamental Blocks> Electrical Sources. Drag and drop AC Voltage
Source
●​ Choose Simscape> Electrical> Specialized Power Systems>
Fundamental Blocks> Elements.Drag and drop the Series RLC Branch
●​ Select appropriate values for the elements
●​ Search Voltage Measurement, Powergui and Scope and connect them accordingly
●​ Observe the output of the signal

Figure-1

Figure-2
●​ Choose Step from the Library Browser and observe the output.

Figure-3

Figure-4
●​ Choose Pulse Generator from the Library Browser and observe the output and observe the
output.

Figure-5

Figure-6
Lab Report: [10]
3 3 2
1.​ Plot cos(sin(x +6)) and sin(x )*cos(x -5) on the interval [-2pi, 2pi] using
spacing 0.05 on the same figure. Attach a label and a title to this plot.

Class Task: [5]


1.​ Observe the output of uniform random number, unit step and ramp function using
Simulink.
Experiment No. 2
Modelling of dynamic systems
1.​ Objective: This experiment is intended to familiarize the students with Electrical systems,
generation of system equations, Transfer functions, poles, and zeroes
PART-A
2.​ Introduction:
●​ 1st Order Circuit:
A first-order circuit can only contain one energy storage element (a capacitor or an inductor). The circuit will
also contain resistance. So there are two types of first-order circuits:
1.​ RC Circuit
2.​ RL Circuit

●​ 2nd Order Circuit


Second-order circuits are RLC circuits that contain two energy storage elements. They can be represented
by a second-order differential equation. A characteristic equation, which is derived from the governing
differential equation, is often used to determine the natural response of the circuit.

A first-order circuit will contain only one energy element, where an energy element is an inductor or
capacitor. A second-order circuit will contain two energy elements. A third-order circuit will contain three
energy elements.

3. Software and Device requirements:

●​ MATLAB
●​ Simulink

Minimum PC specifications:
Windows/Mac: Microsoft® Windows® 7 Professional, Enterprise, Ultimate or Home Premium (64-bit);
Windows 8 (64-bit) (All Service Packs); Windows 10 (64-bit); Windows 2008 R2 Server; Windows 2012
Server (All Service Packs).
Ram: 2 GB
Processor: Intel® Pentium® 4 or AMD Athlon XP 2000 with multi-core CPU
Display resolutions: 1,024 x 768 display resolution with true color (16-bit color)
4. Simulink Model and Output:
a.​ 1st Order RC Circuit:
●​ Type Simulink in the command window or click on the Simulink icon
●​ Chose Blank Model from the window
●​ Construct the following circuit and observe the output voltage across the “Capacitor”

Figure-1: First-Order RC Circuit

Figure-2: Output across “Capacitor”


b.​ 2nd Order RLC Circuit:
●​ Type Simulink in the command window or click on the Simulink icon
●​ Chose Blank Model from the window
●​ Construct the following circuit and observe the output voltage across the “Capacitor”

Figure-3:Second-Order RLC Circuit

Figure-4: Output across “Capacitor”


PART-B
st
In this part, we will analyze a simple 1 order RC circuit and generate its output for simple step input using
mathematical and simulation techniques.

Figure-1: RC Circuit Schematic


Applying laws of KVL,
𝑉𝑠(𝑡) = 𝑉𝑟(𝑡) + 𝑉𝑐(𝑡)
𝑑𝑣𝑐(𝑡)
𝑉𝑠(𝑡) − 𝑉𝑐(𝑡) = 𝑅𝐶 𝑑𝑡
Taking Laplace Transform and assuming zero-initial state,
𝑉𝑐(𝑠) + 𝑠𝑅𝐶𝑉𝑐(𝑠) = 𝑉𝑠(𝑠)
1
𝑉𝑐(𝑠) 𝑠𝑐 1
𝐻(𝑠) = 𝑉𝑠(𝑠)
= 1 = 𝑅𝐶𝑠+1
𝑅+ 𝑠𝑐
Let, R = 50000 Ohm and C = 100pF
Here, H(s) is the transfer function of the system and is the mathematical description of the system. Using
H(s) we can find the response (output) of the system for any given input. In this study, we will deal with
step inputs only. When input is a step function, the output of the system is called a “step response”.Since,
practical systems are extremely difficult to solve analytically, it is useful to learn simulation
techniques for computing responses of LTI systems.
MATLAB Technique for solving step responses:
R = 50000;
C = 100e-12;
m = R*C;
num = 1;
den = [m 1];
h = tf(num,den);
step(h);

Output:

Figure-2: Output of Step Function


The step function computes and automatically plots the step response. If you want to plot using regular
MATLAB commands, then use the following code:
MATLAB Code:
R = 50000;
C = 100e-12;
m = R*C;
num = 1;
den = [m 1];
h = tf(num,den);
step(h);
[y time] = step(h);

Simulink-based computation of step response:


1. Form a Simulink-based model for the RC system and simulate the step response.
2. Tweak the parameters of each block for a better understanding of the process.

Figure-3: LTI System for RC Circuit

Figure-4: Output of Step Response


●​ Determination of Poles and Zeros:
Poles and Zeros of a transfer function are the frequencies for which the value of the denominator and
numerator of the transfer function becomes zero respectively. The values of the poles and the zeros of a
system determine whether the system is stable, and how well the system performs.
MATLAB Code:
R = 50000;
C = 100e-12;
m = R*C;
num = 1;
den = [m 1];
h = tf(num,den);
[z,p,k]=tf2zp(num,den)
pzmap(h)

Lab Report:
Consider a First-order RC (series RC Circuit) circuit with an input voltage source (Step). The output
Voltage is observed across the Capacitor. Use the following values
R = 5000Ω, C = 0.005F.
●​ Plot the step response of the circuit using following methods:
a) using MATLAB coding [2.5]
b) using Simulink LTI block [2.5]
●​ Determine Zeros, Poles and gain [2.5]
●​ Explain how the system response can be varied with proper simulation illustration. [2.5]
Experiment No. 3
State Space Analysis
1.​ Objective:
●​ Fundamentals of State Space Analysis
●​ State Space in Matrix Form
●​ State Space Simulation Diagram

PART-A

2.​ Introduction:
State Space

State Space is the set of all possible and known states of a system. In state-space, each unique
point represents a state of the system. State Space Model is a mathematical model in control
engineering. State-space models are models that use state variables to describe a system by a
set of first-order differential or difference equations, rather than by one or more nth-order
differential or difference equations. State variables in this model are a type of variable whose
value changes over time and depends on the values that have been given for the input
variables. The value of the output variables depends on the value of the state and input
variables. Putting a model into state-space representation is the basis for many methods in
control analysis and the dynamics process. In general, a state space is introduced into a system
description without examining its specific physical meaning. It is known, however, that if we
select a suitable state-space representation, it becomes easier for us to understand or
manipulate the property of a system.

Figure-1: System Inputs and Outputs


The State Equations

A standard form for the state equations is used throughout system dynamics. In the standard
form the mathematical description of the system is expressed as a set of n coupled first-order
ordinary differential equations, known as the state equations, in which the time derivative of
each state variable is expressed in terms of the state variables x1(t),...,xn(t) and the system
inputs u1(t),...,ur(t). In the general case, the form of the n state representation is expressed as
Eqs. (1):

For an LTI system of order n, and with r inputs, Eqs. (1) become a set of n coupled first-order
linear differential equations with constant coefficients:

We can also write the Equation in Matrix Form:

Which may be summarized as:

where the state vector x is a column vector of length n, the input vector u is a column vector of
length r, A is an n × n square matrix of the constant coefficients aij , and B is an n × r matrix of
the coefficients bij that weight the inputs.
Output equations
An arbitrary output variable in a system of order n with r inputs may be written:

where the ci and di are constants. If a total of m system variables are defined as outputs,
the m such equations may be written as:

or in matrix form:

We can write the equation in the compact format as:

State Equation-Based Modeling Procedure

The complete system model for a linear time-invariant system consists of (i) a set of n state
equations, defined in terms of the matrices A and B, and (ii) a set of output equations that relate
any output variables of interest to the state variables and inputs, and expressed in terms of the
C and D matrices. The task of modeling the system is to derive the elements of the matrices,
and to write the system model in the form:

The matrices A and B are properties of the system and are determined by the system structure
and elements. The output equation matrices C and D are determined by the particular choice of
output variables. The overall modeling procedure developed in this chapter is based on the
following steps:
1. Determination of the system order n and selection of a set of state variables from the linear
graph system representation.
2. Generation of a set of state equations and the system A and B matrices using a well-defined
methodology. This step is also based on the linear graph system description.
3. Determination of a suitable set of output equations and derivation of the appropriate C and D
matrices.
Block Diagram Representation of Linear Systems Described by
State Equations
The matrix-based state equations express the derivatives of the state variables explicitly in
terms of the states themselves and the inputs. In this form, the state vector is expressed as the
direct result of vector integration. The block diagram representation is shown in Fig. 2. This
general block diagram shows the matrix operations from input to output in terms of the A, B, C,
and D matrices, but does not show the path of individual variables. In state-determined systems,
the state variables may always be taken as the outputs of integrator blocks. A system of order n
has n integrators in its block diagram. The derivatives of the state variables are the inputs to the
integrator blocks, and each state equation expresses a derivative as a sum of weighted state
variables and inputs. A detailed block diagram representing a system of order n may be
constructed directly from the state and output equations as follows:
Step 1: Draw n integrator (S−1) blocks, and assign a state variable to the output of each block.
Step 2: At the input to each block (which represents the derivative of its state variable) draw a
summing element.
Step 3: Use the state equations to connect the state variables and inputs to the summing
elements through scaling operator blocks.
Step 4: Expand the output equations and sum the state variables and inputs through a set of
scaling operators to form the components of the output.

Figure 2: Vector block diagram for a linear system described by state-space system dynamics.
PART-B
Let us consider the case for parallel RLC Circuit. Here, R = 40 ohm, L = 4H, C = 0.25F

Figure-3: Parallel RLC Circuit

Here, Current (i) and Voltage (v) are state variables. Now, using KCL, we get:
Note:
●​ Output can be a state variable
●​ Now replace the values in the respective variables and determine the State Space
Equation and Output Equation

PART-C

Figure-4: Series RLC Circuit

The Transfer Function for Fig-4 is :

After replacing the values of respective elements, we finally get:


MATLAB Code:
●​ Type the following code in your script:

R = 40;
L = 4;
C = 0.25;
num = 1;
den = [L*C R*C 1];
h = tf(num,den)

Output:

●​ Now type the following line in the command window:

[A,B,C,D]=tf2ss(num,den)

●​ You will see the following Matrices for A, B, C, and D:

●​ Now, type “Simulink” in the command window.


●​ Build the following circuit:
Figure 5: Simulink Model for Transfer Function and State Space

●​ Observe the Outputs of individual scopes.

Output:

Figure 6: Output through Mux

Lab Report:
●​ Model the State Space Representation (State Equation and Output Equation) for
2nd Order Series RLC Circuit. Determine A, B, C, D Matrices for the system (By
Derivation).You can assume appropriate element values for your convenience.
(you can attach the photo/scan of your derivation in your report). [5]
●​ Observe and compare the step response for the system by both Transfer
Function Method and State Space Method. Write a proper discussion about the
system's behavior. [5]
Experiment No. 4
Linearization of nonlinear model
1.​ Objective:
●​ Linearization of a nonlinear system through time-varying continuous function

2.​ Introduction:
One of the approaches to obtaining the models for the system design is based on analysis of
the system dynamics using first principles, such as mass balance, Newton’s laws, current law,
and voltage law. The majority of practical models are nonlinear in nature. We cannot solve most
nonlinear models, so we often try to get an overall feel for the way the model behaves: we
sometimes talk about looking at the qualitative dynamics of a system. Linear models are easier
to understand (than nonlinear models) and are necessary for most control system design
methods. In order to linearize general nonlinear systems, we will use the Taylor Series
expansion of functions. The Taylor series provides a means to predict a function value at one
point in terms of the function value and its derivatives at another point. Linearization is a linear
approximation of a nonlinear system that is valid in a small region around an operating point.
For example, suppose that the nonlinear function is y = x2 Linearizing this nonlinear function
about the operating point x = 1, y = 1 results in a linear function y = 2x−1.

Figure 1: Comparison of Linear and Nonlinear Model


3.​ Procedure:
Let’s assume a general single variable function f(x) represents the nonlinear behavior of a
system. The function f(x) can be approximated by a Taylor series approximation around the
steady-state operating point (xs)

Since we are focused on linearization, we will only focus on putting the formulation as Y=MX+C
Now, neglecting the quadratic and higher order terms, we get,

The partial derivative of f(x) with respect to x, evaluated at the steady-state

This criterion is also known as first-order Taylor Series Approximation.

MATLAB CODE:
syms x
f = x^2+3*x;
X = input('X:');
Xs = input('Xs:');
d = X-Xs;
df=diff(f);
fvals=eval(subs(f,Xs));
dfvals=eval(subs(df,Xs));
Y = fvals+dfvals*d
y = eval(subs(f,X))
Error = (abs(y-Y)/y)*100 % True Percentage Relative Error
Output:
>> Test
X:2
Xs:1.9
Y =
9.9900
y =
10
Error =
0.1000
Practical Application of Linearization:
Courtesy by: Jaisohn Kim VT

Class Task:
Linearize the following function where the operating point Xs = 3 and the approximated point
X = 3.17. Find out the percentage relative true error.
3 2
Current through a RL Circuit can be expressed as - I(t) = 8x -7x +5x+19
Experiment No. 5
Least square method: Determination of polynomial
using method of Least Square Curve Fitting
1.​ Objective:
●​ Fitting a polynomial curve into a least square linear line model

2.​ Introduction:
The least squares method is a statistical procedure to find the best fit for a set of data points by
minimizing the sum of the offsets or residuals of points from the plotted curve. Least squares
regression is used to predict the behavior of dependent variables. The least squares principle
states that by getting the sum of the squares of the errors at a minimum value, the most
probable values of a system of unknown quantities can be obtained upon which observations
have been made. The most common application of this method, which is sometimes referred to
as "linear" or "ordinary," aims to create a straight line that minimizes the sum of the squares of
the errors that are generated by the results of the associated equations, such as the squared
residuals resulting from differences in the observed value, and the value anticipated, based on
that model. Line of best-fit equations may be determined by computer software models, which
include a summary of outputs for analysis, where the coefficients and summary outputs explain
the dependence of the variables being tested. Outliers can have a disproportionate effect if you
use the least squares fitting method of finding an equation for a curve. This is because the
squares of the offsets are used instead of the absolute value of the offsets; outliers naturally
have larger offsets and will affect the line more than points closer to the line. These
disproportionate values may be beneficial in some cases.

Figure 1: Linear Least Square Regression


●​ Data are often given for discrete values along a continuum. However, you may require
estimates at points between the discrete values. Hence, we fit curves to such data to
obtain intermediate estimates.
●​ Sometimes, it may require a simplified version of a complicated function. One way to do
this is to compute values of the function at a number of discrete values along the range
of interest. Then, a simpler function may be derived to fit these values.
●​ The simplest example of a least-squares approximation is fitting a straight line to a set of
paired observations: (x1 , y1 ), (x2 , y2 ), . . . , (xn , yn ). The mathematical
expression for the straight line is

●​ where a0 and a1 are coefficients representing the intercept and the slope, respectively,
and e is the error, or residual, between the model and the observations.
●​ The equation of the error of the fitted curve can be rewritten as

●​ Thus, the error, or residual, is the discrepancy between the true value of y and the
approximate value, a0 + a1x, predicted by the linear equation.
●​ The target is to minimize the error. Hence, we need a criterion for reducing the error (e).
●​ We need to minimize the squared error function:

●​ Setting these derivatives equal to zero will result in a minimum Sr . If this is done, the
equations can be expressed as:
●​ Solving this system of two equations, we can derive the values of a0 and a1, which are
for the lowest regression error.

MATLAB CODE:

●​ First, we will create a User Function in MATLAB to perform the Least


Square Regression problem.
●​ After that, we will execute our model using a script.

User Defined Function Code:

function [a1, a0] = linear_regression(x,y)

n = length(x);
sum_x = sum(x(:));
sum_y = sum(y(:));
square_x = sum(x(:).*x(:));
sum_xy = sum(x(:).*y(:));

a1 = ((n * sum_xy) - (sum_x * sum_y)) / ((n * square_x) - (sum_x*sum_x));

mean_y = sum_y / n;
mean_x = sum_x / n;
a0 = mean_y - a1 * mean_x;

end
MATLAB Script Code:
clear all
close all
clc

% Take the value where we are interested to see output value


P = input('P:');

%Define the data

x = [1,2,3,4,5,6,7];
y = [.5,2.5,2.0,4,3.5,6,5.5];

[a1,a0] = linear_regression(x,y); %Implements simple least square linear regression

%Find the approximated values for all the data points

Y = [];
for i = 1:0.1:20
c = a0 + a1 * i;
Y = [Y c];
end
D = a0 + a1 * P

%y = contains true function points


%Y = contains approximated function points using the regression line
%D = contains approximated function value

s = 1:0.1:20;
plot(s,Y,x,y,'*');
legend('regression Line', 'Data Points');

Output:

P:5.5

D =

4.6875
Figure 2: Comparison of Data Points and Least Square Regression Line
Experiment No. 6
Numerical methods for differential equations: Linear
system simulation
1.​ Objective:
●​ To understand and apply Forward, Backward, and centered divided difference schemes
for Numerical Differentiation

2.​ Introduction:
Finite Divided Difference is useful for determining the differentiation value numerically. There are
usually three different kinds of finite divided difference formulas used usually –

●​ Forward Finite Divided Difference


●​ Backward Finite Divided Difference
●​ Central Finite Divided Difference

Part-1:Forward Divided Difference

Fig.1: Graphical depiction of Forward divided-difference approximations of the first derivative.

The Taylor series for finding the next value of a function based on the present value is –
If we truncate the series after the first derivative term, we will get,

where ∆fi is referred to as the first forward difference and h is called the step size, that is, the
length of the interval over which the approximation is made. It is termed a “forward” difference
because it utilizes data at i and i+1 to estimate the derivative. The entire term ∆fi/h is referred to
as a first-order finite forward divided difference.

Part-2:Backward Divided Difference

Fig.2: Graphical depiction of Backward divided-difference approximations of the first derivative.

The Taylor series for finding the previous value of a function based on the present value is
represented as-

If we truncate the series after the first derivative term, we will get,

Where ∇fi is referred to as the first backward difference and h is called the step size, that is, the
length of the interval over which the approximation is made. It is termed a “backward” difference
because it utilizes data at i and i-1 to estimate the derivative. The entire term ∇fi/h is referred to
as a first-order finite backward divided difference.
Part-1:Central Divided Difference

Fig.3: Graphical depiction of Central divided-difference approximations of the first derivative.

Central divided difference formula can be obtained by subtracting equation 3 from equation 1.

Since,

We get,

After algebraic manipulations,

This equation is termed as first order finite central divided difference. Notice that the truncation
error is of the order of h2 in contrast to the forward and backward approximations that were of
the order of h. Consequently, the Taylor series analysis yields the practical information that the
centered difference is a more accurate representation of the derivative than forward or
backward difference.
MATLAB CODE:
% User Defined Function for Forward Divided Difference
function value = forward_difference(f,x,h,o,i)
%f = derivative function
%x = the value at which the derivative has to be evaluated
%h = divided difference
%o = Order of the derivative
%i = takes the values either 1 or 2; 2 denotes more accurate results

if(o == 1 && i == 1)
value = (f(x+h)-f(x))/h;
elseif(o == 1 && i == 2)
value = (-f(x + 2*h) + 4*f(x+h) - 3*f(x))/(2*h);
elseif(o == 2 && i == 1)
value = (f(x+2*h)-2*f(x+h)+f(x))/(h*h);
elseif(o == 2 && i == 2)
value = (-f(x+3*h)+ 4*f(x+2*h)-5*f(x+h)+2*f(x))/(h*h);
elseif(o == 3 && i == 1)
value = (f(x+3*h) - 3*f(x+2*h) + 3*f(x+h) - f(x))/(h^3);
elseif(o == 3 && i == 2)
value = (-3*f(x+4*h) + 14*f(x+3*h) - 24*f(x+2*h) + 18*f(x+h) - 5*f(x))/(2*(h^3));
elseif(o == 4 && i == 1)
value = (f(x+4*h) - 4*f(x+3*h) + 6*f(x+2*h) - 4*f(x+h) + f(x))/(h^4);
elseif(o == 4 && i == 2)
value = (-2*f(x+5*h) + 11*f(x+4*h) - 24*f(x+3*h) + 26*f(x+2*h) - 14*f(x+h) + 3*f(x))/(h^4);
end

end

% User Defined Function for BAckward Divided Difference

function value = backward_difference(f,x,h,o,i)


%f = derivative function
%x = the value at which the derivative has to be evaluated
%h = divided difference
%o = Order of the derivative
%i = takes the values either 1 or 2; 2 denotes more accurate results

if(o == 1 && i == 1)
value = (f(x)-f(x-h))/h;
elseif(o == 1 && i == 2)
value = (3*f(x) - 4*f(x-h) + f(x-2*h))/(2*h);
elseif(o == 2 && i == 1)
value = (f(x)-2*f(x-h)+f(x-2*h))/(h*h);
elseif(o == 2 && i == 2)
value = (2*f(x) - 5*f(x-h) + 4*f(x-2*h) - f(x-3*h))/(h^2);
elseif(o == 3 && i == 1)
value = (f(x) - 3*f(x-h) + 3*f(x-2*h) - f(x-3*h))/(h^3);
elseif(o == 3 && i == 2)
value = (5**f(x) - 18*f(x-h) + 24*f(x-2*h) - 14*f(x-3*h) + 3*f(x-4*h))/(2*(h^3));
elseif(o == 4 && i == 1)
value = (f(x) - 4*f(x-h) + 6*f(x-2*h) - 4*f(x-3*h) + f(x-4*h))/(h^4);
elseif(o == 4 && i == 2)
value = (3*f(x) - 14*f(x-h) + 26*f(x-2*h) - 24*f(x-3*h) + 11*f(x-4*h) - 2*f(x-5*h))/(h^4);
end
end
% User Defined Function for Central Divided Difference

function value = central_difference(f,x,h,o,i)


%f = derivative function
%x = the value at which the derivative has to be evaluated
%h = divided difference
%o = Order of the derivative
%i = takes the values either 1 or 2; 2 denotes more accurate results

if(o == 1 && i == 1)
value = (f(x+h)-f(x-h))/(2*h);
elseif(o == 1 && i == 2)
value = (-f(x + 2*h) + 8*f(x+h) - 8*f(x-h) + f(x-2*h))/(12*h);
elseif(o == 2 && i == 1)
value = (f(x+h)-2*f(x)+f(x-h))/(h*h);
elseif(o == 2 && i == 2)
value = (-f(x+2*h) + 16*f(x+h) - 30*f(x) + 16*f(x-h) - f(x-2*h))/(12*h*h);
elseif(o == 3 && i == 1)
value = (f(x+2*h) - 2*f(x+h) + 2*f(x-h) - f(x-2*h))/(2*(h^3));
elseif(o == 3 && i == 2)
value = (-f(x+3*h) + 8*f(x+2*h) - 13*f(x+h) + 13*f(x-h) - 8*f(x-2*h) + f(x-3*h))/(8*(h^3));
elseif(o == 4 && i == 1)
value = (f(x+2*h) - 4*f(x+h) + 6*f(x) - 4*f(x-h) + f(x-2*h))/(h^4);
elseif(o == 4 && i == 2)
value = (-f(x+3*h) + 12*f(x+2*h) + 39*f(x+h) + 56*f(x) - 39*f(x-h) + 12*f(x-2*h) +
f(x-3*h))/(6*(h^4));
end

end

Differentiation Script:

clc;
clear all;
close all;
syms x
f1 = x^4+3*x^2;
df=diff(f1)
y=inline(df);
x= input('Enter your x value: ');
true_val1 = y(x);
f=inline(f1);
h = [];
value = [];
error = [];
for i=1:6;
hi=10^(-i);
h= [h hi];
valuei = forward_difference(f,1,hi,1,1);
value = [value valuei];
errori = abs((true_val1-valuei)/true_val1)*100;
error = [error errori];
end
disp(h);
disp(value);
disp(error);
Result:

df =

4*x^3 + 6*x

Enter your x value: 1


0.1 0.01 0.001 0.0001 1e-05 1e-06

10.941 10.09 10.009 10.001 10 10

9.41 0.90401 0.09004 0.0090004 0.00090001 8.9995e-05

>>
Formulae for Forward Divided Difference:

Formulae for Backward Divided Difference:

Formulae for Central Divided Difference:


Experiment No. 7
Runge-Kutta Discretization: Solution Methodology for
Ordinary Differential Equations
1.​ Objective:
●​ To understand and apply Runge-Kutta Discretization for Ordinary Differential Equations
2.​ Introduction:
Runge-Kutta (RK) methods achieve the accuracy of a Taylor series approach without requiring
the calculation of higher derivatives. The Runge-Kutta Method was developed by two German
men Carl Runge (1856-1927), and Martin Kutta (1867- 1944) in 1901. The most widely known
member of the Runge–Kutta family is generally referred to as "RK4", the "classic Runge–Kutta
method" or simply as "the Runge–Kutta method".

The general form of the Runge-Kutta method is:

where Фn(xi, yi, h) is called an increment function, which can be interpreted as a representative
slope over the interval.

where the a’s are constants, the k’s in the increment function are defined as:

where the p’s and q’s are constants, notice that the k’s are recurrence relationships. That is, k1
appears in the equation for k2, which appears in the equation for k3, and so forth.
4th Order RK Method:
The classical RK method of fourth order is-

MATLAB CODE:

[4th Order RK Method]


function [X,Y] = RK_4(f,a1,a2,a3,a4,p1,q11,p2,q21,q22,p3,q31,q32,q33,h,xi,yi,xf)
x = xi;
y = yi;
X = [x];
Y = [y];

while(x <= xf)


k1 = f(x,y);
k2 = f(x+p1*h,y+q11*k1*h);
k3 = f(x+p2*h,y+q21*k1*h+q22*k2*h);
k4 = f(x+p3*h,y+q31*k1*h+q32*k2*h+q33*k3*h);
y = y + (a1*k1+a2*k2+a3*k3+a4*k4)*h;
x = x+h;
X = [X x];
Y = [Y y];
end
end
RK METHOD SCRIPT:
clear all
close all

f = inline('-2.*(x.^3)+12.*(x.^2)-20.*x+8.5','x','y');
xi = 0;%initial data point
yi = 2;%initial value
xf = 4;%final data point
h = 0.5;%step size
[X,Y] = RK_4(f,1/6,1/3,1/3,1/6,0.5,0.5,0.5,0,0.5,1,0,0,1,h,xi,yi,xf);
plot(X,Y);
legend('4th Order RK');
grid on
title('Runge-Kutta Method')
xlabel('X')
ylabel('Y')

OUTPUT:

Figure: 4th Order RK Method


Lab Report:
Use the classical fourth-order RK method to integrate the following function using a step size of h=0.25
and an initial condition of y=1.5 at x=0. Solve for x=0 to 4.5.
Experiment No. 8
Introduction to system identifications using Matlab.
1.​ Objective:
●​ To develop a model of a dynamic systems using data.

2.​ Introduction:
System identification is a methodology used to develop mathematical models of dynamic
systems using measurements of the input and output signals of the system.
The process involves:
●​ Measuring the input and output signals from the system in time or frequency domain.
●​ Identifying a model structure.
●​ Applying an estimation method to estimate values for the adjustable parameters in the
candidate model structure.
●​ Evaluating the estimated model to see if the model is adequate for your application
needs.
A model is a mathematical relationship between the input and output variables of the system.
Models of dynamic systems are typically described by differential equations, transfer functions,
state-space equations, and pole-zero-gain models. However, dynamic models can be
represented in both continuous-time and discrete-time form.
System identification uses the input and output signals of a system to estimate the values of
adjustable parameters in a given model structure. One can build models using time-domain
input-output signals, frequency response data. To obtain a good model we must have measured
data which reflects the dynamic behavior of the system and the accuracy of the model depends
upon the quality of the data, which in turn depends on the experimental design.

Time-Domain Data
Time-domain data consists of the input and output variables of the system recorded at a uniform
sampling interval over a period of time. Now, for creating such a model, input vector u, output
y and the sampling time TS are sufficient.

Data Quality Requirements


System identification requires that the data captures all the important dynamics of the targeted
system. Good experimental design ensures the measurement of the right variables with
sufficient accuracy and duration to capture the dynamics we wish to model. In general, we must:
●​ Use inputs that excite the system dynamics adequately. For example, a single step is
seldom enough excitation.
●​ Measure data long enough to capture the important time constants.
●​ Set up a data acquisition system that has a good signal-to-noise ratio.
●​ Measure data at appropriate sampling intervals or frequency resolution.
Build Models from Data
Model Structure: A model structure is a mathematical relationship between input and output
variables that contains unknown parameters. Examples of model structures are transfer
functions with adjustable poles and zeros, state-space equations with unknown system
matrices, and nonlinear parameterized functions.
The following difference equation represents a simple model structure:
y(k)+a y(k−1) = b u(k) Here, a and b are adjustable parameters.
The system identification process requires that to choose a model structure and apply the
estimation methods to determine the numerical values of the model parameters.
One of the following approaches can be used to choose the model structure:

●​ Black-box modeling: A model that is able to reproduce the measured data and is as
simple as possible. Black-box modeling is useful when one’s primary interest is in fitting
the data regardless of a particular mathematical structure of the model. Black-box
modeling is usually a trial-and-error process, where we estimate the parameters of
various structures and compare the results. Typically, one start with the simple linear
model structure and progress to more complex structures.
●​ Grey-box modeling: A specific structure of the model, in some situations, one can
deduce the model structure from physical principles. We can represent the model
structure as a set of equations or as a state-space system in MATLAB and estimate the
values of its parameters from data. This approach is known as grey-box modeling.

Estimate Model Parameters: The System Identification software estimates model parameters
by minimizing the error between the model output and the measured response. The output ymodel
(t) of the linear model is given by
ymodel (t) = G u(t) where, G is the transfer function.
To determine G, the toolbox minimizes the difference between the model output ymodel (t) and the
measured output ymeasured(t). The minimization criterion is the error, v(t), where
v(t) = ymeasured(t) - ymodel (t).
The error v(t) is called the simulation error or prediction error. The estimation algorithms adjust
parameters in the model structure G such that the error is as small as possible.

Useful Matlab Commands:

y = lsim(sys,u,t)
returns the system response y of the dynamic system model sys for input signal u. The
vector t specifies the sampling time for the simulation.

data = iddata(y,u,Ts)
creates an iddata object containing a time-domain output signal y and input signal u. Ts is the
sampling time. System identification functions use these measurements to estimate a model
and model validation functions use it to compare how well the estimated model response fits the
original data.
sys = tfest(data,np,nz);
sys is an idtf model containing the estimated transfer function that uses poles and zeros to
estimate the transfer function. Here iddata object is given as input along with number of poles
(np) and zeros (nz).

opt = compareOptions('InitialCondition','z');
Compare the estimated transfer function model output to the measured data using the
comparison option set. An option set is created to specify the initial condition handling. To use
zero for initial conditions, specify 'z' for the 'InitialCondition' option.

compare(data,sys,opt)
to compare identified model output with measured output. Here iddata object is given as input
along with estimated model and compare options.

sys = ssest(data,nx)
estimates the continuous-time state-space model sys of order nx, using all the input and output
signals in the iddata object.

Model of an actual RLC system:

Figure 1: Series RLC Circuit

Value of R,L and C are given as: 5 Ohm, 2 H and 0.25 F respecively.

The Transfer Function for Fig1 is:


Estimation of model using pole and zero:
MATLAB CODE:

R = 5;
L = 2;
C = 0.25;
num = 1;
den = [L*C R*C 1];
sys_real = tf(num,den) % Transfer Function

dt=.01;
t=0:dt:12;
u=ones(length(t),1);

t1=0;
t2=1;
id=find(t>=t1 & t<=t2);
u(id)=0;

y_real = lsim(sys_real,u,t); % to get actual system response

figure(1)
plot(t,[u, y_real])
legend('U','Y real')
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')

% Fit data to an unknown transfer function

data=iddata(y_real,u,dt); % create iddata object before identification


np=1; % number of poles
nz=0; % number of zeros
sys_aprox=tfest(data,np,nz)
y_approx = lsim(sys_aprox,u,t); % to get approximate system response

% Comparison of systems

opt = compareOptions('InitialCondition','z');
[ymod,fit,ic] = compare(data,sys_aprox,opt)

y_vector = get( ymod, 'outputData' );


figure(2)
plot(t,[u, y_real, y_vector])
legend('U','Y real',"Y approx with "+fit+ "% fit")
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')
%% Testing the model performance on another input

% Create input patterns


t_test=0:dt:12;
u_test=ones(length(t_test),1);

t1=0;
t2=0.5;
id=find(t_test>=t1 & t_test<=t2);
u_test(id)=0;

t1=3;
t2=6;
id=find(t_test>=t1 & t_test<=t2);
u_test(id)=0.5;

t1=8;
t2=10;
id=find(t_test>=t1 & t_test<=t2);
u_test(id)=0.75;

figure(3)
plot(t_test,u_test)
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')

% Testing system response on new input


y_real_test = lsim(sys_real,u_test,t_test);
y_approx_test = lsim(sys_aprox,u_test,t_test);

% Comparison of systems on new input

data_test=iddata(y_real_test,u_test,dt);

[ymod,fit,ic] = compare(data_test,sys_aprox,opt)
y_vector_test = get( ymod, 'outputData' );

figure(4)
plot(t_test,[u_test, y_real_test, y_vector_test])
legend('U','Y real',"Y approx with "+fit+ "% fit")
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')
Output:
Transfer functions:

Graphs:

Figure 2: Actual System Response of Series RLC Circuit


Figure 3: Actual and Estimated System Response of Series RLC Circuit

Figure 4: New Input for Validation Purpose


Figure 5: Actual and Estimated System Response of Series RLC Circuit on New Input

Estimation of model using state space:


MATLAB CODE:

R = 5;
L = 2;
C = 0.25;
num = 1;
den = [L*C R*C 1];
sys_real = tf(num,den) % Transfer Function

dt=.01;
t=0:dt:12;
u=ones(length(t),1);

t1=0;
t2=1;
id=find(t>=t1 & t<=t2);
u(id)=0;

y_real = lsim(sys_real,u,t); % to get actual system response


figure(1)
plot(t,[u, y_real])
legend('U','Y real')
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')
% Fit data to a state space model of unknown order

data=iddata(y_real,u,dt); % create iddata object before identification


nx=1:10; % order of model
Gss=ssest(data,nx); % to select optimum model
sys_aprox=tf(Gss) % to get transfer function
y_approx = lsim(sys_aprox,u,t); % to get approximate system response

% Comparison of systems

opt = compareOptions('InitialCondition','z');
[ymod,fit,ic] = compare(data,sys_aprox,opt)

y_vector = get( ymod, 'outputData' );


figure(2)
plot(t,[u, y_real, y_vector])
legend('U','Y real',"Y approx with "+fit+ "% fit")
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')

%% Testing the model performance on another input

% Create input patterns


t_test=0:dt:12;
u_test=ones(length(t_test),1);

t1=0;
t2=0.5;
id=find(t_test>=t1 & t_test<=t2);
u_test(id)=0;

t1=3;
t2=6;
id=find(t_test>=t1 & t_test<=t2);
u_test(id)=0.5;

t1=8;
t2=10;
id=find(t_test>=t1 & t_test<=t2);
u_test(id)=0.75;

figure(3)
plot(t_test,u_test)
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')

% Testing system response on new input


y_real_test = lsim(sys_real,u_test,t_test);
y_approx_test = lsim(sys_aprox,u_test,t_test);
% Comparison of systems on new input

data_test=iddata(y_real_test,u_test,dt);

[ymod,fit,ic] = compare(data_test,sys_aprox,opt)
y_vector_test = get( ymod, 'outputData' );

figure(4)
plot(t_test,[u_test, y_real_test, y_vector_test])
legend('U','Y real',"Y approx with "+fit+ "% fit")
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')

Output:
Select 1st order model in model order selection and click Apply.

Transfer functions:
Graphs:

Figure 6: Actual and Estimated System Response of Series RLC Circuit


Figure 7: Actual and Estimated System Response of Series RLC Circuit on New Input

Assignment:
a)​ Change the R and L value to 2 and 1 respectively. Observe the output of actual
and estimated model using pole zero and state space estimation for simple step
input. Make a comment which model is more suitable. [3]

b)​ Create a new test input pattern for input voltage (3,8,2, last_digit_of_your_id) to
observe the output using both the model created (trained with simple step input)
in (a). [6]

c)​ Change the number of poles only and change the model order for the case of
state space to observe the actual and estimated system response of simple step
input. Observe the system response for test input pattern generated in (b) and
compare the responses how it is changing with number of poles and model order.
Find the optimum number of poles and model order. [6]

REFERENCE: System Identification Overview, Help Center, MathWorks.

You might also like