What is wrong with this loop?

1 次查看(过去 30 天)
for kn=1:199
for snn=1:6591
for sn=1:3
if x1c{kn+1,1}(snn,sn)-x1c{kn,1}(snn,sn)>20
x1c{kn+1,1}(snn,sn)=x1c{kn+1,1}(snn,sn)+40; %EXTENDED POSITION(1)
elseif x1c{kn+1,1}(snn,sn)-x1c{kn,1}(snn,sn)<-20
x1c{kn+1,1}(snn,sn)=x1c{kn+1,1}(snn,sn)-40; %EXTENDED POSITION(2)
else
x1c{kn+1,1}(snn,sn)=x1c{kn+1,1}(snn,sn);
end
end
end
end
It doesn't give any error, but I think it does do something wrong.
  1 个评论
Matthew Eicholtz
Matthew Eicholtz 2016-2-29
If it doesn't give any error, then the only way to know if it is doing something wrong is to know what the purpose of the code is in the first place. So, what do you expect the code to do?

请先登录,再进行评论。

采纳的回答

Roger Stafford
Roger Stafford 2016-2-29
My guess is that the outer for-loop which changes kn, starting from kn = 1 and ending with kn = 199 is causing unexpected results. For example, for kn = 1, the values of x1c{2,1}(1,1) and x1c{1,1}(1,1) are used to determine what the next value of x1c{2,1}(1,1) will be. It is either to have 40 added, 40 subtracted, or left as is. Unfortunately, at the next value of kn = 2, the altered value of x1c{2,1}(1,1) is used to determine the next change to x1c{3,1}(1,1) rather than the original value of x1c{2,1}(1,1), and that can lead to an unplanned result.
This can all be corrected by making the outer loop go backwards:
for kn = 199:-1:1
.....
end
In that case there will be no such changes made to elements that will be used in the future for making other changes.
An additional observation is that the step
else
x1c{kn+1,1}(snn,sn) = x1c{kn+1,1}(snn,sn);
accomplishes absolutely nothing and can be removed altogether. Why burden matlab with so much extra labor which changes nothing?
  3 个评论
Roger Stafford
Roger Stafford 2016-2-29
Be careful of the kisses. Tomorrow I will become a nonagenarian and not nearly as good-looking as in the displayed image.
fert
fert 2016-2-29
From your soul then:)! Thank you man, thank you Sir!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by