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.
empty( sizeVector ) returns an empty array with the specified dimensions. At least one of the dimensions must be 0. Use this syntax to define an empty array that is the same size as an existing empty array. Pass the values returned by the size function as inputs.
The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .
Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement. For example, create a handle to an anonymous function that finds the square of a number: sqr = @(x) x.
Passing an anonymous function as a function handle to other functions: For the constructions of higher functions, we can pass an anonymous function as the function handle to other functions. For example, create a function handle with input parameter as func(output of the anonymous function), and x.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With