how to run a for loop for a varying no. of times in matlab?

Hi everyone. I need your help again. Is there any way to run a for loop for suppose k no. of times where the value of k is changing with each iteration of the loop??
Suppose the program is:
n=7; %fixed
k=0;
for i=1:n+k
statements;
statements;
if(condition is true)
k=k+1;
end
end
The loop is being executed for n times even if condition is true and k gets incremented. But I want the loop to run for n+k no. of times. Is it possible? Is there any workaround?? Please help! Thanx in advance!!

 Respuesta aceptada

Amit
Amit el 19 de En. de 2014
You can use while loop something like this:
n=7; %fixed
k=0;
val_flag = 0;
while (val_flag < n+k)
statements;
statements;
if(condition is true)
k=k+1;
val_flag = val_flag + 1;
end
end

4 comentarios

If i use while instead of for , then program is taking a long long time to run. Also there is a nested for loop inside while loop where it is taking its time. Why this is happening?
There is no for-loop in the code that Amit has shown...
roro6992
roro6992 el 19 de En. de 2014
Editada: roro6992 el 19 de En. de 2014
Sry i hd to mention. I have one nested for loop inside the while loop too. But its index doesnt need to be changed its fixed. I bother about the first for loop...or while loop as he suggested.
Amit
Amit el 19 de En. de 2014
haha .. I am just worried that the inside k = k+1 will go to a long long time. I hope you have some condition where you stop growing k.
And, please post the whole code, so that people can see. One will only answer what you ask. We can't know the twists and turns in the story.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Centro de ayuda y File Exchange.

Preguntada:

el 19 de En. de 2014

Comentada:

el 19 de En. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by