1

Is there an easy way to make a for loop count down instead of up?

I know that I can do something like this:

for i = 1:100
    % do stuff
end

But I need the numbers in the opposite order. When I do this:

for i = 100:1
    % do stuff
end

It says that 'i' is an empty matrix.

1 Answer 1

4

You could simply flip the looping variable. This has the benefit of working for any arbitrary looping variable.

for i = flip(1:100)
end

For your specific example, you could specify a negative increment value for the colon operator

for i = 100:-1:1
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.