如何退出此功能?

时间:2017-11-14 19:50:37

标签: matlab

基本上它是这样构建的:

.If

..other stuff

.Else

..For

...For

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

我已尝试使用returnbreak,但他们因任何原因无法正常工作。我添加了一个自动收报机,似乎break命令不起作用?

代码只是继续进行并重复for循环,即使它被打破了#39;在If声明中。

我的功能只有大约150行,所以我能够仔细研究它,这似乎是问题所在。

1 个答案:

答案 0 :(得分:1)

如果你有

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

你只会突破内部循环。但是,当然,外部循环将继续正常进行!

打破嵌套循环是goto极少数合理用例之一。但是,MATLAB没有goto,所以你必须以某种方式重复自己:

for (...)

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

    if (condition) 
        break;

end

同样丑陋却又不那么冗长的方式:

try 

    for (...)

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


catch %#ok

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

end

或者,是迂腐的,

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

或者您构建一个仅包含该嵌套循环的(嵌套)函数,并使用return来突破。但这可能并不总是给出最“明显”的代码结构,并且导致你必须编写大量的样板代码(子函数)和/或有无法预见的副作用(嵌套函数),所以...

就个人而言,我赞成上面的try/catch

相关问题