Cutting a for loop when a certain value is repeated
Mostrar comentarios más antiguos
Is there any way of cutting a for loop when a certain value is reached? I have a loop in the form of
for k = 1:numel(filelist)
this loop produces a value of X at the end of every loop which is then stored in a text file. I was just wondering whether there is any way that the for loop can be cut when this value of X stops increasing/ stays the same?
I thought something maybe along the lines of
if X(k-1)==X(k)
break
end
but this doesn't work. I guess its because the loop overwrites X. I was just wondering whether anyone had any ideas? Thanks in advance!
Respuestas (2)
Azzi Abdelmalek
el 16 de Abr. de 2014
It's better to use a while loop
while x(k-1)~=x(k)
% your code
end
1 comentario
Sean de Wolski
el 16 de Abr. de 2014
Sure, pseudocode:
xtemp = nan;
for ii = 1:1000
x = whatever
do stuff
if x==xtemp
break
else
xtemp = x;
end
end
4 comentarios
Sean de Wolski
el 16 de Abr. de 2014
Editada: Sean de Wolski
el 16 de Abr. de 2014
ii is just the for loop iterator. I set xtemp to nan because nothing equals nan. This means the first iteration will run through no matter what and the second is the first that can fail. After that, on each iteration, we test if the new x is equal to the old one, if it is, break, if it isn't don't break and store the new current value for x in xtemp for the next iteration.
Jed
el 16 de Abr. de 2014
Jed
el 16 de Abr. de 2014
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!