我如何使“空"商品MATLAB中的匿名函数? [英] How do I make an "empty" anonymous function in MATLAB?

查看:77
本文介绍了我如何使“空"商品MATLAB中的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MATLAB中进行调试时,我使用匿名函数进行诊断打印.例如,

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

disp([])用作吞噬"对我来说似乎有点肮脏;有更好的选择吗?显而易见的(?)方法不起作用:

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.

推荐答案

您可以在代码库中添加常规的虚无功能.

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;

现在,它有点自我记录,可以清楚地表明您打算什么也不做,而不是抓住了disp()的错误输入.在源代码中将显而易见,此外,当您在调试器中并检查包含函数句柄的变量时,它将显示为"@NOP",它比匿名句柄更具可读性.通过查看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.

您还可以使用Matlab的内置@deal,在退化的情况下,它不执行任何操作,也不返回任何内容.

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

这篇关于我如何使“空"商品MATLAB中的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆