Issue with simulating linear system using lsim inside a for loop

조회 수: 5 (최근 30일)
J AI
J AI 2021년 10월 13일
댓글: J AI 2021년 10월 14일
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!

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by