How can I write a condition statement in for loop?

6 次查看(过去 30 天)
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 ?

回答(1 个)

Image Analyst
Image Analyst 2018-2-17
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 个评论
zeezo
zeezo 2018-2-17
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by