Borrar filtros
Borrar filtros

How can I write a condition statement in for loop?

6 visualizaciones (últimos 30 días)
zeezo
zeezo el 17 de Feb. de 2018
Comentada: zeezo el 17 de Feb. de 2018
I have this code. I want if the a=>6 the code increase k by one and go back from the beginning of the for loop. how can I do it ?
k=4;
b=[2,5,2,6,3,4,5,9,10,2,9,4,6,8,7,3,4];
c=[5,2,5,6,9,8,3,1,6,5,5,3,6,4,1,6,9];
for i=1:k
a=b(1,i)+c(1,i);
ss(1,i)=a;
if a>6 then % this does not work
k=k+1
end
end
ss
The code I wrote does not work. How can I write this condition ?

Respuestas (1)

Image Analyst
Image Analyst el 17 de Feb. de 2018
Try this:
kMax = 4;
thisK = 1;
maxIterations = 10000; % Some number larger than you ever expect.
b=[2,5,2,6,3,4,5,9,10,2,9,4,6,8,7,3,4];
c=[5,2,5,6,9,8,3,1,6,5,5,3,6,4,1,6,9];
loopCounter = 1;
while loopCounter <= length(c) && ...
thisK < kMax && ...
loopCounter < maxIterations
a = b(loopCounter) + c(loopCounter);
ss(loopCounter) = a;
if a > 6
thisK = thisK+1
end
loopCounter = loopCounter + 1;
end
ss
  3 comentarios
zeezo
zeezo el 17 de Feb. de 2018
Also why do we use kMax ?
zeezo
zeezo el 17 de Feb. de 2018
I run the code but it does not come up with what I want
kMax =5 ;
thisK = 1;
maxIterations = 10000; % Some number larger than you ever expect.
b=[2,5,2,6,3,4,5,9,10,2,9,4,6,8,7,3,4];
c=[5,2,5,6,9,9,3,1,6,5,5,3,6,4,1,6,9];
loopCounter = 1;
while loopCounter <= length(c) && ...
thisK < kMax && ...
loopCounter < maxIterations
a = b(loopCounter) + c(loopCounter);
ss(loopCounter) = a;
if a > 9
thisK = thisK+1;
end
loopCounter = loopCounter + 1;
end
ss
the result was
ss =
7 7 7 12 12 13 8 10
the condition is that it will run 5 times then in the last one if the a>9 will make anther loop. Then if the new a>9 it will run again and if it less than 9 it will stop but here a =8 and it it still running for one extra loop

Iniciar sesión para comentar.

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by