For loop with Else statement
Mostra commenti meno recenti
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 Commenti
Guillaume
il 10 Ott 2018
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
il 11 Ott 2018
Risposta accettata
Più risposte (2)
KALYAN ACHARJYA
il 10 Ott 2018
Modificato: KALYAN ACHARJYA
il 10 Ott 2018
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 Commenti
Miroslav Mitev
il 11 Ott 2018
KALYAN ACHARJYA
il 11 Ott 2018
Modificato: KALYAN ACHARJYA
il 11 Ott 2018
@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
il 11 Ott 2018
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;
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!