필터 지우기
필터 지우기

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 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