For loop with Else statement
이전 댓글 표시
Hi all! I am running a loop of the form:
RR=flip(1:100);
CC=0;
threshold=3000;
for i=1:100
if CC<threshold
C_old=CC;
CC=sum(RR(1:i));
else
CC=C_old;
RR(i)=0;
end
end
The problem is when the loop passes through the else statement it automatically increase "i" by 1. Which leads to skipping values of the vector "RR". How can I fix this?
댓글 수: 2
Guillaume
2018년 10월 10일
it automatically increase "i" by 1
It certainly doesn't so if that really happens it's because you have written code that explicitly does it.
We would need to see the actual code for us to tell you what is happening.
Miroslav Mitev
2018년 10월 11일
채택된 답변
추가 답변 (2개)
KALYAN ACHARJYA
2018년 10월 10일
편집: KALYAN ACHARJYA
2018년 10월 10일
for i=1:100
if b(i)>1
do something
else
do something else
end
end
No, this cant, except "do something else" statement include i=i+1, other any other i increment statement.
For Example
b=-5:1:100
c=1;
for i=1:100
if b(i)>1
disp(b(i));
else
c=c+1;
end
end
댓글 수: 2
Miroslav Mitev
2018년 10월 11일
KALYAN ACHARJYA
2018년 10월 11일
편집: KALYAN ACHARJYA
2018년 10월 11일
@Miroslavi value is not skipped (I checked it by disp(i))
RR=flip(1:100);
CC=0;
threshold=3000;
for i=1:100
if CC<threshold
disp(i);
C_old=CC;
CC=sum(RR(1:i));
else
disp(i);
CC=C_old;
RR(i)=0;
end
end

Dennis
2018년 10월 11일
My guess is that you want to set every value in RR to 0 after the cumulative sum reaches 3000.
Here is why this does not work:
CC is the sum of RR(1:i), once CC reaches 3001 you enter your else statement. In your else statement:
CC=C_old; % you set CC to zero
RR(i)=0;
In the next iteration of your loop CC will initially be 0. Hence it enters your if statement:
CC=sum(RR(1:i)); %this will be >3001
So basically from here on your loop will alternate between if and else.
Now i am not completly sure what you want to do, if my assumption was correct that you want to set values in RR to 0 after the sum reaches a specific value you can try this code:
RR=100:-1:1;
A=cumsum(RR);
RR(A>3000)=0;
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!