Issue with simulating linear system using lsim inside a for loop
4 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Time and Frequency Domain Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!