What is wrong with this loop?

1 visualización (últimos 30 días)
fert
fert el 29 de Feb. de 2016
Comentada: fert el 29 de Feb. de 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 comentario
Matthew Eicholtz
Matthew Eicholtz el 29 de Feb. de 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?

Iniciar sesión para comentar.

Respuesta aceptada

Roger Stafford
Roger Stafford el 29 de Feb. de 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 comentarios
Roger Stafford
Roger Stafford el 29 de Feb. de 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 el 29 de Feb. de 2016
From your soul then:)! Thank you man, thank you Sir!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by