1

Is it possible to have the start of a for-loop within an if-statement. For example:

if condition true 

    for j=1:10 

else % condition false

    for j=11:20

end % End of if-statement

    % inner part of for-loop

end % End of for-loop

I know this is not the most beautiful approach, but in some cases it might be easier than simple coding.

1 Answer 1

6

No, that doesn't work.

But you can do

if condition
    range=1:10
else % condition false
    range=11:20
end % End of if-statement

for j=range
    % inner part of for-loop
end % End of for-loop
Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution. If things are more complicated (e.g. you may need to use both ranges sequentially) you can also just put the loop in a function, and call the function with the proper range at different spots.
@DennisJaheruddin This is right, but is essentially a special version of this solution when/where range is a parameter of this function.

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.