退出文件后启动MATLAB调试模式

退出文件后启动MATLAB调试模式,matlab,debugging,Matlab,Debugging,我经常发现自己处于这样的境地,我在代码中插入了大量的键盘命令来调试代码。不过,我希望有更多的灵活性。这就是为什么我开始编写我的stahp函数 function stahp() disp('Stahp requested.'); dbstack disp('You can either'); disp(' 1 abort.'); disp(' 2 continue.'); disp(' 3 debug.'); in = input('Choose what to do:\n'); swi

我经常发现自己处于这样的境地,我在代码中插入了大量的
键盘
命令来调试代码。不过,我希望有更多的灵活性。这就是为什么我开始编写我的
stahp
函数

function stahp()
disp('Stahp requested.');
dbstack
disp('You can either');
disp('  1 abort.');
disp('  2 continue.');
disp('  3 debug.');

in = input('Choose what to do:\n');

switch(in)
    case 1
        error('Stahp.');
    case 2
        disp('Continue.')
    case 3
        disp('Debug.');
        keyboard % <------------------------------------ Here is my problem
    otherwise
        stahp();
end
end
我想在
b=2
之前进入调试模式。我假设可以以某种方式使用
dbstep out
,但按照我目前尝试的方式,您仍然必须手动退出
stahp()
。我还知道,在
中递归调用
stahp()
,否则可能会使事情复杂化,但我可以删除该部分


非常感谢您的帮助。谢谢。

您可以使用
dbstack
获取当前堆栈,然后检索调用
stahp
的调用函数名称和行号。使用此信息,您可以使用
dbstop
在执行函数调用的函数中创建断点。下面的代码示例在b=2行的
test\u stahp
中设置断点

function stahp()
disp('Stahp requested.');
dbstack
disp('You can either');
disp('  1 abort.');
disp('  2 continue.');
disp('  3 debug.');

in = input('Choose what to do:\n');
r=dbstack;
switch(in)
    case 1
        dbclear(r(2).name,num2str(r(2).line+1));
        error('Stahp.');
    case 2
        dbclear(r(2).name,num2str(r(2).line+1));
        disp('Continue.')
    case 3
        disp('Debug.');
        dbstop(r(2).name,num2str(r(2).line+1))
    otherwise
        stahp();
end
end

这种方法有一个问题。如果选择“调试”
,则会在下一行显式放置断点。但是如果我重新运行代码并选择继续,我仍然会在最初放置的断点处停止。谢谢您指出。一个选项是使用
dbclear
清除断点。我更新了现有答案,以便删除断点(如果有)。谢谢,但是现在,
stahp
还没有完成。我不希望每次添加
stahp
时都添加
dbclear
。是的,更好的方法可能是在“stahp”的开头调用“dbclear”。这样,每次调用断点时,都会清除所有旧断点。明天有机会测试后,我会更新代码。看来,在
continue
error
案例中添加
dbclear(r(2).name,num2str(r(2.line+1))
可以解决问题。文件开头的一个简单的
dbclear
将清除所有断点。如果你能在你的回答中包含这一点,我会接受它作为解决方案。
function stahp()
disp('Stahp requested.');
dbstack
disp('You can either');
disp('  1 abort.');
disp('  2 continue.');
disp('  3 debug.');

in = input('Choose what to do:\n');
r=dbstack;
switch(in)
    case 1
        dbclear(r(2).name,num2str(r(2).line+1));
        error('Stahp.');
    case 2
        dbclear(r(2).name,num2str(r(2).line+1));
        disp('Continue.')
    case 3
        disp('Debug.');
        dbstop(r(2).name,num2str(r(2).line+1))
    otherwise
        stahp();
end
end