How to integrate a control system by ode45 with PID control input ?

25 views (last 30 days)
I want to simulate a control system using ode45 function. The system model can be expressed as , where the control input u is the PID control which can be expressed as . The is the desired state. My question is how to integrate the error in the ode model as illustrated in the following code example, since we only obtain the current time state X when the f function is called
function dX = f(t,X,P)
% ...
% ...
u = P.Kp * (P.Xd - X) + P.Ki * (P.Xd - X) + ... ; % How to integrate the error Xd - X ?
end

Accepted Answer

Sam Chak
Sam Chak on 20 Nov 2025 at 15:25
Perhaps you can try this approach.
G = tf(1, [1, 0, 0]);
opt = pidtuneOptions('DesignFocus', 'disturbance-rejection');
wc = 5;
C = pidtune(G, 'PID', wc, opt);
% Parameters
P.Xd = 3; % desired state for X(1)
P.Kp = C.Kp; % proportional gain
P.Ki = C.Ki; % integral gain
P.Kd = C.Kd; % derivative gain
% ODE function
function dX = f(t, X, P)
% error
e = P.Xd - X(1);
% PID controller
u = P.Kp*e + P.Ki*X(3) - P.Kd*X(2);
% disturbance
d = 1;
% original 2nd-order system
dX(1) = X(2);
dX(2) = d + u;
% X(3) is ∫ e dt
dX(3) = e;
% system dynamics
dX = [dX(1)
dX(2)
dX(3)];
end
% Solve and plot
[t, X] = ode45(@(t, X) f(t, X, P), [0, 10], zeros(3, 1));
plot(t, X(:,1)), grid on
title('Time response for state x_{1}')
xlabel('t')
ylabel('x_{1}')

More Answers (1)

Torsten
Torsten on 20 Nov 2025 at 14:19
Add a second differential equation
dV/dt = P.Xd - X
with initial condition
V(0) = 0
Then
V(t) = integral_{0}^{t} (P.Xd - X) dt

Products


Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!