Issue with simulating linear system using lsim inside a for loop

4 vues (au cours des 30 derniers jours)
J AI
J AI le 13 Oct 2021
Commenté : J AI le 14 Oct 2021
s = tf('s');
Gm = 2163/(s^2 + 80*s + 2163);
samplingTime = 2e-3;
totalTime = 0.5;
time = 0:samplingTime:totalTime;
r = 80;
% Using for loop
ym(1,:) = 0;
for k = 2:length(time)
ym(k,:) = ReferenceModel(Gm,r,samplingTime,ym(k-1,:));
end
% Without for loop
ym2 = lsim(Gm,r*ones(size(time)),time);
hold on
plot(time,ym,'b')
plot(time,ym2,'r--')
legend('ym','ym2')
function ym = ReferenceModel(Gm,r,samplingTime,y0)
tspan = 0:samplingTime/10:samplingTime;
ym = y0 + lsim(Gm,r*ones(size(tspan)),tspan);
ym = ym(end);
end
I am not sure why the output produced using the for loop (ym) does not produce the same result as the one without the for loop (ym2)? I know ym2 is correct so has to be some mistake in my ReferenceModel function. Please kindly help me so that I can produce the same result using for loop.
Thanks in advance!

Réponse acceptée

Paul
Paul le 13 Oct 2021
Modifié(e) : Paul le 13 Oct 2021
Each step in ReferenceModel has to use an intiial state that is the final state from the previous step. Using that term y0 is incorrect. In order to keep track of the state vector, it appears a ss object is required as the input in the call to lsim()
s = tf('s');
Gm = 2163/(s^2 + 80*s + 2163);
samplingTime = 2e-3;
totalTime = 0.5;
time = 0:samplingTime:totalTime;
r = 80;
% Using for loop
ym(1,:) = 0; xm = [0;0]; % initial state
for k = 2:length(time)
[ym(k,:),xm] = ReferenceModel(Gm,r,samplingTime,xm); % send in state from prvevious time step
end
% Without for loop
ym2 = lsim(Gm,r*ones(size(time)),time);
hold on
plot(time,ym,'bo')
plot(time,ym2,'r--')
legend('ym','ym2')
function [ym,xm] = ReferenceModel(Gm,r,samplingTime,x0)
tspan = 0:samplingTime/10:samplingTime;
[ym,~,xm] = lsim(ss(Gm),r*ones(size(tspan)),tspan,x0); % use ss form and use initial state correctly
ym = ym(end);
xm = xm(end,:);
end
  2 commentaires
J AI
J AI le 14 Oct 2021
Thanks a lot for pointing that out! Works just as wanted
J AI
J AI le 14 Oct 2021
trying to accept your answer but getting this error even after reloading :/

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Time and Frequency Domain Analysis dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by