Matlab 调用fprintf或disp时如何抛出错误?

Matlab 调用fprintf或disp时如何抛出错误?,matlab,debugging,error-handling,Matlab,Debugging,Error Handling,我有一个庞大的无法穿透的代码库,它写出了非常恼人的换行符。由于某种奇怪的原因,我似乎找不到他们在哪里。所以我在想,只要调用sprintf或disp,我就能让MATLAB抛出一个错误,我就能找到它们。有办法做到这一点吗 我尝试了evalc,但它提供的只是输出本身,而不是从调用它的位置发出的。我不建议抛出错误。例如,无论何时退出调试器,workspacefunc都会调用disp。设置断点会更容易,如果需要错误,请将键盘替换为错误 function disp( varargin ) builtin('

我有一个庞大的无法穿透的代码库,它写出了非常恼人的换行符。由于某种奇怪的原因,我似乎找不到他们在哪里。所以我在想,只要调用
sprintf
disp
,我就能让MATLAB抛出一个错误,我就能找到它们。有办法做到这一点吗


我尝试了
evalc
,但它提供的只是输出本身,而不是从调用它的位置发出的。

我不建议抛出错误。例如,无论何时退出调试器,workspacefunc都会调用disp。设置断点会更容易,如果需要错误,请将
键盘
替换为错误

function disp( varargin )
builtin('disp',varargin{:});
x=dbstack;
%it's nessecary to exclude all calls which come via workspacefunc,
%otherwise it's impossible to quit the debugger.
if numel(x)>2&&strcmpi(x(2).file,'workspacefunc.m')
    return;
end
keyboard;
end

将此disp.m放置在路径顶部,它将调用内置项,这样您就可以看到打印的内容,并在之后停止。对fprint执行相同的操作,您可以编写自己的disp()函数(这可能会使用error()函数生成错误),并将其保存为当前Matlab路径中的disp.m。这将覆盖内置disp()&允许您找到调用它的位置


或者,您可以用记事本++之类的工具打开库中的所有文件,并在所有打开的文件中搜索术语“disp”(

使
fprintf
抛出错误非常容易,因为
fprintf
没有重载方法

您可以通过在当前目录中创建一个名为fprintf.m的新函数(该函数在Matlab路径中始终是最高的)来隐藏内置的
fprintf
。该函数应包含如下代码:

function fprintf(varargin)
error('Error message to help find fprintf statements')
现在,当您运行不可穿透代码时,只要调用
fprintf
,就会出现错误

如果无法穿透的代码更改了目录,您的新fprintf.m可能不会被调用。在这种情况下,我会将您的自定义fprintf.m代码放在Matlabs路径上高于Matlabs
fprintf
函数的文件夹中。您可以通过在命令行中发出以下命令来检查它是否更高:

which fprintf -all
>> testdbstop
3   disp(x)
K>> dbstack
> In testdbstop at 3
K>> dbcont
     1
6           fprintf('%d\n',x);
K>> dbstack
> In testdbstop>fprintTest at 6
  In testdbstop at 4
K>> dbcont
1
Matlab的内置函数应该是阴影,而你的函数应该在顶部。它应该是这样的:

function fprintf(varargin)
error('Error message to help find fprintf statements')
哪个FPRINF-all C:\Users\MyName\Documents\MATLAB\fprintf.m C:\ProgramFiles(x86)\MATLAB\R2009a\toolbox\MATLAB\iofun\@serial\fprintf.m%串行方法 内置(C:\ProgramFiles(x86)\MATLAB\R2009a\toolbox\MATLAB\iofun\fprintf)%Shadowed

由于存在许多不同的disp方法,因此查找正在生成变量的缺少分号更加困难。

当然你可以重载
disp
fprintf
,或者你可以告诉调试器使用
dbstop
停止这些函数。然后使用
dbstack
查看你在哪里以及你是如何到达那里的。这些内置函数没有MATLAB代码是可以的。它将在调用之前停止:

>> dbstop in disp Warning: MATLAB debugger can only stop in MATLAB code files, and "libmwbuiltins>disp" is not a MATLAB code file. Instead, the debugger will stop at the point right before "libmwbuiltins>disp" is called. >> dbstop in fprintf Warning: MATLAB debugger can only stop in MATLAB code files, and "libmwbuiltins>fprintf" is not a MATLAB code file. Instead, the debugger will stop at the point right before "libmwbuiltins>fprintf" is called. 从命令行运行它:

which fprintf -all
>> testdbstop
3   disp(x)
K>> dbstack
> In testdbstop at 3
K>> dbcont
     1
6           fprintf('%d\n',x);
K>> dbstack
> In testdbstop>fprintTest at 6
  In testdbstop at 4
K>> dbcont
1
这里有它--disp在
testdbstop.m
的第3行调用,而
fprintf
testdbstop.m
的第6行调用,在
testdbstop>fprintTest
中,fprintTest从
testdbstop
的第4行调用

注意:完成后,使用
dbclear
(即disp中的
dbclear
和fprintf中的
dbclear)删除虚拟断点