What is wrong with this loop?

1 visualizzazione (ultimi 30 giorni)
fert
fert il 29 Feb 2016
Commentato: fert il 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 Commento
Matthew Eicholtz
Matthew Eicholtz il 29 Feb 2016
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?

Accedi per commentare.

Risposta accettata

Roger Stafford
Roger Stafford il 29 Feb 2016
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 Commenti
Roger Stafford
Roger Stafford il 29 Feb 2016
Be careful of the kisses. Tomorrow I will become a nonagenarian and not nearly as good-looking as in the displayed image.
fert
fert il 29 Feb 2016
From your soul then:)! Thank you man, thank you Sir!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by