MATLAB禁止在函数中放置disp()实例的命令行 [英] MATLAB suppress command line put of disp() instances in a function
问题描述
在一个函数中,我有一些disp()实例来帮助跟踪较长的计算过程的进度.
In a function, I have a few instances of disp() to help keeping track of the progress of a long computation process.
例如,
function myfun(inputs)
...
disp('Step i finished')
...
end
在myfun
的某些其他用法中,没有disp()
消息更为方便.有没有一种方法可以在不添加新代码或不使用eval()
函数的情况下抑制命令行中的步骤i完成"消息?
In some other usage of myfun
, it is more convenient not having the disp()
messages. Is there a way to suppress the message 'Step i finished' in command line WITHOUT either adding new code OR using the eval()
function?
注意:已知eval()
对于任何严肃的计算来说都太慢了.
Note: eval()
is known to be too slow for any serious computation.
推荐答案
在MATLAB中,没有机制可以重定向"stdout
".您可以使用evalc
捕获它,然后将其忽略,但这也可以捕获(并因此取消)所有警告.同样,所有使用eval
的常见反对意见均适用.
There is no mechanism to redirect "stdout
" in MATLAB. You can capture it with evalc
and then ignore it, but that also captures (and thus suppresses) all warnings. Also, all the usual objections to using eval
apply.
如果您坚持,则可以使用此错误的错误 Bad 黑客:
If you insist then you can use this bad bad BAD hack:
disp = @(~) display([]); %# at the start of the function
或者,如果您真的不想更改函数中的单个字母,请放
or, if you really don't want to change a single letter in your function, put
function disp(~)
在MATLAB路径上的单独M文件中,并在完成后从MATLAB路径中删除其路径(或删除/重命名文件).
in a separate M-file on the MATLAB path, and remove its path from the MATLAB path (or remove/rename the file) when you're done.
但是,实际上,最好的方法是重写您的函数,以便显示是可选的,并且/或者显示级别是可调的.例如,就像几乎所有MATLAB自带的函数一样:
But really, the best way is to rewrite your function so that display is optional, and/or the level of display tunable. For example, like in virtually all of MATLAB's own functions:
options = optimset('Display', 'iter-detailed');
[~] = fminsearch(@cos, 3, options);
spparms('spumoni', 2);
sparse(rand(4)) \ rand(4,1)
这篇关于MATLAB禁止在函数中放置disp()实例的命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!