Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 如何退出此函数?_Matlab - Fatal编程技术网

Matlab 如何退出此函数?

Matlab 如何退出此函数?,matlab,Matlab,基本上它是这样建造的: .If ..other stuff .Else ..For ...For ....If (this is where I need to be able to break out of the whole thing) 我试过使用return和break,但无论出于什么原因,它们都不起作用。我添加了一个股票代码,似乎break命令不起作用了 即使在If语句中的for循环“中断”后,代码仍会继续运行并重复for循环 我的函数只有大约150行长,所以我能够仔细研究

基本上它是这样建造的:

.If

..other stuff

.Else

..For

...For

....If (this is where I need to be able to break out of the whole thing)
我试过使用
return
break
,但无论出于什么原因,它们都不起作用。我添加了一个股票代码,似乎
break
命令不起作用了

即使在
If
语句中的for循环“中断”后,代码仍会继续运行并重复for循环

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

如果你有

for (...)
    for (...)
        if (true) 
            break;
    end
end
你只会打破内部循环。但是,当然,外部循环将继续正常运行

打破嵌套循环是
goto
为数不多的合理用例之一。但是,MATLAB没有转到,因此您必须以某种方式重复自己的操作:

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

为什么
return
不起作用?为了补充gnovice的评论-为什么不将两个循环放在一个单独的函数中,然后在完成时返回
return
?我知道为什么break不起作用,我怀疑返回失败的原因与此相同,它只是在退出if语句后继续for循环。我想我也要尝试一下,因为这是一个作业,所以我只能使用1(自制)函数,这是作业本身。谢谢!最后一个似乎正是我需要的!我剩下的大部分代码也在这两个for循环中,这并不理想,这太完美了!