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

查看:35
本文介绍了我如何制作“空"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天全站免登陆