Andrew I
Andrew I

Reputation: 11

How do I exit this function?

Essentially its built like so:

.If

..other stuff

.Else

..For

...For

....If (this is where I need to be able to break out of the whole thing)

I've tried using return, and break, but they just are not working for whatever reason. I added in a ticker and it appears that the break command isn't working?

The code just continues going on and repeating the for loop even AFTER it is 'broken' in the If statement.

My function is only about 150 lines long, so I've been able to study it closely, and this seems to be where the problem is.

Upvotes: 1

Views: 52

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

If you have

for (...)
    for (...)
        if (true) 
            break;
    end
end

you'll only break out of the inner loop. But, of course, the outer loop will continue as normal!

Breaking out of nested-loops is one of the very few reasonable use cases for a goto. However, MATLAB does not have a goto, so you'll have to repeat yourself in some way or another:

for (...)

    for (...)
        if (condition) 
            break;
    end

    if (condition) 
        break;

end

An equally ugly yet common and less verbose way:

try 

    for (...)

        for (...)
            if (condition) 
                error(' ');
        end       
    end


catch %#ok

    (code you want to be executed after the nested loop)

end

or, to be pedantic,

breakout_ID = 'fcn:breakout_condition';

try 

    for (...)

        for (...)
            if (condition) 
                error(breakout_ID, ' ');
        end       
    end


catch ME

    % graceful breakout
    if strcmp(ME.Identifier, breakout_ID)
        (code you want to be executed after the nested loop)

    % something else went wrong; throw that error
    else
        rethrow(ME);
    end

end

Or you build a (nested) function containing just that nested loop, and use return to break out. But that may not always give the most "obvious" code structure, as well as cause you to have to write lots of boilerplate code (subfunction) and/or have unforeseen side effects (nested functions), so...

Personally, I favor the try/catch above.

Upvotes: 1

Related Questions