フィルターのクリア

How can I write a condition statement in for loop?

6 ビュー (過去 30 日間)
zeezo
zeezo 2018 年 2 月 17 日
コメント済み: zeezo 2018 年 2 月 17 日
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 日
Also why do we use kMax ?
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by