Search code examples
matlabfor-loopcontinue

MATLAB 'continue' command alternative


for i = 1:30
    if condition1
        statement1
    elseif condition2
        continue
    else
        statement2
    end
    statement3
end

As above, I have 'continue' command in a for loop to skip 'statement3' if condition2 is satisfied. This code works well. But when I have to run the if-else part for test purpose, it makes an error because 'continue' should be run within a for/while loop.

Is there a way to do the same thing (do nothing and skip to the next iteration) in a for loop but also works separately?


Solution

  • If you want to run the exact same code outside a loop, hence without being able to use continue, you can simply rewrite it as follows:

    if ~condition2
        if condition1
            statement1
        else
            statement2  
        end
    
        statement3
    end
    

    Alternatively (I know it's not very elegant, but it does work indeed):

    if condition1
        statement1
        statement3
    elseif condition2
    else
        statement2  
        statement3
    end
    

    The above code be improved (a lot) by rewriting it as follows:

    if condition1
        statement1
        statement3
    elseif ~condition2
        statement2  
        statement3
    end
    

    Finally, if your statement3 is particularly long and you don't want to repeat it twice, you can further improve the code above using a bypass flag:

    go3 = false;
    
    if condition1
        statement1
        go3 = true;
    elseif ~condition2
        statement2  
        go3 = true;
    end
    
    if go3
        statement3
    end
    

    The problem is that abstract conditions don't allow me to use my imagination at full potential. Maybe if you specify the conditions you are using, even in a simplified way, I could try to come up with a better solution.