0

发生无限递归时Matlab崩溃,如下代码

文件:xm

function x
     y;
end

档案:ym

function y
     x;
end

文件:脚本.m

x;

如果脚本 script.m 被执行 matlab crash 并且必须重新启动。

即使我使用了 try-catch,它仍然会崩溃:

文件:脚本.m

try
x;
catch
    error('stack-overflow');
end

有没有办法处理无限循环中省略的这种崩溃?

4

1 回答 1

1

作为一个快速的技巧,你可以做

global counter;
global RecursionDepth;
counter = 0;
RecursionDepth = 1000;

在你的代码开头的某个地方,那么你可以做

function IncrementCounterAndCheckDepth()

    global counter;
    global RecursionDepth;
    counter = counter+1;
    if counter > RecursionDepth
    error('stack-overflow');
else
disp(RecursionDepth);
    end;
    return;

and insert it whenever necessary to check recursion. You can even add additional info/pass some arguments to it to improve your debugging, and once you are done with debugging, you can remove all globals and define IncrementCounterAndCheckDepth() to do nothing, so performance will not be affected, and for debugging it can be inserted in a lot of places without affecting performance. If you ever need to do additional debugging, you simply turn this function back on and modify is as required to track particular issue - you know it is everywhere in your code.

于 2013-01-06T17:32:47.560 回答