MATLAB Answers

fert
0

What is wrong with this loop?

Asked by fert
on 29 Feb 2016
Latest activity Commented on by fert
on 29 Feb 2016
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 Comment

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?

Sign in to comment.

Tags

1 Answer

Answer by Roger Stafford on 29 Feb 2016
 Accepted Answer

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 Comments

Roger, I want to kiss you.
Be careful of the kisses. Tomorrow I will become a nonagenarian and not nearly as good-looking as in the displayed image.
From your soul then:)! Thank you man, thank you Sir!

Sign in to comment.