For loop with Else statement
Mostrar comentarios más antiguos
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 comentarios
Guillaume
el 10 de Oct. de 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
el 11 de Oct. de 2018
Respuesta aceptada
Más respuestas (2)
KALYAN ACHARJYA
el 10 de Oct. de 2018
Editada: KALYAN ACHARJYA
el 10 de Oct. de 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 comentarios
Miroslav Mitev
el 11 de Oct. de 2018
KALYAN ACHARJYA
el 11 de Oct. de 2018
Editada: KALYAN ACHARJYA
el 11 de Oct. de 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
el 11 de Oct. de 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;
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!