How do I make an “empty” anonymous function in MATLAB?

半腔热情 提交于 2019-12-08 14:50:29

问题


I use anonymous functions for diagnostic printing when debugging in MATLAB. E.g.,

debug_disp = @(str) disp(str);
debug_disp('Something is up.')
...
debug_disp = @(str) disp([]);
% diagnostics are now hidden

Using disp([]) as a "gobble" seems a bit dirty to me; is there a better option? The obvious (?) method doesn't work:

debug_disp = @(str) ;

This could, I think, be useful for other functional language applications, not just diagnostic printing.


回答1:


You could add a regular do-nothing function to your codebase.

function NOP(varargin)
%NOP Do nothing
%
% NOP( ... )
%
% A do-nothing function for use as a placeholder when working with callbacks
% or function handles.

% Intentionally does nothing

Then you can use a function handle to it instead of to an anonymous function wherever you want to no-op something out.

debug_disp = @NOP;

Now it's somewhat self-documenting, making it explicit that you intended to do nothing, instead of grabbed the wrong input for disp(). It will be apparent in the source code, plus, when you're in the debugger and examining variables holding function handles, it'll show up as "@NOP", which may be more readable than an anonymous handle. And you can get a list of all nopped-out operations in the "profile report" output by looking at a list of callers to NOP.

You could also use Matlab's built-in @deal, which in the degenerate case does nothing and returns nothing.




回答2:


I think disp([]) or disp('') is perfectly acceptable. It doesn't return anything and it has no side effects.




回答3:


If you're simply looking for a "do-nothing" command to replace the body of the anonymous function, I'd probably go with DRAWNOW:

debug_disp = @(str) drawnow;

This will simply flush the event queue and update the graphics instead of displaying any text.




回答4:


Here's a do-nothing anonymous function. It does nothing, and returns an empty array, which you can just ignore. You'll need to suppress disp by putting a semicolon after it.

debug_disp = @(str) [];

The disp([]) should work fine too. Whichever style you prefer.




回答5:


try debug_disp = @(str)(1);



来源:https://stackoverflow.com/questions/1904972/how-do-i-make-an-empty-anonymous-function-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!