Filter löschen
Filter löschen

Issue with simulating linear system using lsim inside a for loop

2 Ansichten (letzte 30 Tage)
J AI
J AI am 13 Okt. 2021
Kommentiert: J AI am 14 Okt. 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!

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by