Anonymous functions calling functions with multiple output formats

I am trying to define an anonymous function that calls a version of a function that returns multiple outputs.

For example, the find function has two possible forms of output:

 [row,col] = find(X); 

and

 [ind] = find(X); 

Let's say I would like to select the first form inside an anonymous function.

I tried 1)

 get_columns = @(x) x(2); 

and 2)

 get_columns = @(x,y) y; 

But when I call:

 get_columns(find(x)) 

The first version of get_columns believes that I call find as [ind] = find(X) , and not as [row,col] = find(X); , and the second complains about "Not enough input arguments" .

Is there a way to call a specific output form for a function inside an anonymous function ?

+8
matlab
source share
2 answers

Directly, no. Unfortunately, there are a number of functions that are not available through anonymous functions, and one of them is access to several output arguments. (Another that I often find is that you cannot define an if inside an anonymous function. This is most likely the Matlab syntax more than anything else.

However, a fairly simple helper function can make this possible.

 function varargout = get_outputs(fn, ixsOutputs) output_cell = cell(1,max(ixsOutputs)); [output_cell{:}] = (fn()); varargout = output_cell(ixsOutputs); 

This function takes a function descriptor plus an array of output indices and returns indexed outputs.

If you create this file (hopefully better comment) and put it in your path, you can access the second output of the find function, as by defining the following function

 find_2nd = @(x)get_outputs(@()find(x),2) 

And now you can find the indexes of the array that are 1 as

 >> find_2nd([4 3 2 1]==1) ans = 4 

And now you can access alternative at-will output arguments from anonymous functions.

+8
source share

This get_outputs function above can be widely useful for concise anonymous functions. Very nice.

Also, with regard to the comment that “if” cannot be used in MATLAB, this is only partially true. Identical behavior can be easily implemented anonymously. For example, it is anonymous here if:

 anonymous_if = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}(); 

Using:

 out = anonymous_if(condition1, action1, condition2, action2, ...); 

The action corresponding to the first true condition is performed. For example, it means hello.

 anonymous_if(false, @() disp('hi'), ... % if false, print 'hi' true, @() disp('hello')) % else if true, print 'hello' 

Of course, this is a little complicated at first glance, but I keep something similar in my path, so I can use the “if” in the anonymous function. This way you can build much more complex anonymous functions.

+3
source share

All Articles