EEE - ECE382 - Modelling and Simulation Lab Manual - Spring 2025
EEE - ECE382 - Modelling and Simulation Lab Manual - Spring 2025
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. Mark Distribution
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
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
Yes No
● 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.
● 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
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.
● 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:
eye(i) creates an i x i identity matrix (a matrix of zeros with ones on the diagonal)
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)
Change the limits on the x and y axis. axis([xmin xmax ymin ymax])
● 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)')
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-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.
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.
● 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”
Output:
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.
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:
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:
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
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
R = 40;
L = 4;
C = 0.25;
num = 1;
den = [L*C R*C 1];
h = tf(num,den)
Output:
[A,B,C,D]=tf2ss(num,den)
Output:
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.
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,
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.
● 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:
n = length(x);
sum_x = sum(x(:));
sum_y = sum(y(:));
square_x = sum(x(:).*x(:));
sum_xy = sum(x(:).*y(:));
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
x = [1,2,3,4,5,6,7];
y = [.5,2.5,2.0,4,3.5,6,5.5];
Y = [];
for i = 1:0.1:20
c = a0 + a1 * i;
Y = [Y c];
end
D = a0 + a1 * P
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 –
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.
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
Central divided difference formula can be obtained by subtracting equation 3 from equation 1.
Since,
We get,
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
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
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
>>
Formulae for Forward Divided Difference:
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:
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:
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.
● 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.
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.
Value of R,L and C are given as: 5 Ohm, 2 H and 0.25 F respecively.
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;
figure(1)
plot(t,[u, y_real])
legend('U','Y real')
xlabel('Time (Sec)'),ylabel('Amplitude (Volt)')
% Comparison of systems
opt = compareOptions('InitialCondition','z');
[ymod,fit,ic] = compare(data,sys_aprox,opt)
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)')
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:
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;
% Comparison of systems
opt = compareOptions('InitialCondition','z');
[ymod,fit,ic] = compare(data,sys_aprox,opt)
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)')
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:
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]