Issue with simulating linear system using lsim inside a for loop

9 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Paul
Paul il 13 Ott 2021
Modificato: Paul il 13 Ott 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 Commenti
J AI
J AI il 14 Ott 2021
Thanks a lot for pointing that out! Works just as wanted
J AI
J AI il 14 Ott 2021
trying to accept your answer but getting this error even after reloading :/

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by