Matlab: defining a function descriptor that catches the second return value of a function

Say I have a foo function defined as

  [ab] = foo(c ). 

If I consider a function descriptor

  f = @(c)foo(c) 

for use, for example. in the call to cellfun , what I get is f , acting equivalent to foo , defined as

  a = foo(c) 

i., returns the lost value of b .

Therefore, when such an f is placed in a call to cellfun , the output cell will only have a and will skip b (which I'm worried about right now). Visually

  cellfun(f,input) [a(input{1})] ? [a(input{2})] ? .... b gets killed along the way 

Question: how to define a function descriptor for foo that catches only b s? i.e. gives behavior similar to defining foo as

  b = foo(c) 

ie ^ 2, losing a s.

Also, is it possible to (efficiently) catch both a and b in a unique cellfun call?

+8
matlab function-handle
source share
2 answers

From the cellfun documentation :

[A1, ..., Am] = cellfun (func, C1, ..., Cn) calls the function indicated by the func function of the function and passes the elements from the arrays of cells C1, ..., Cn, where n is the number of inputs for func functions. Output arrays A1, ..., Am, where m is the number of outputs of the func function , contain combined outputs from function calls.

So yes, cellfun can use a function with multiple outputs, in which case it just returns multiple outputs. If you want to use only the second, you can use ~ to ignore the first. The same applies to several outputs of anonymous functions - they will be returned if you specify several output arguments . Here is a simple code:

 function test x{1} = 1; x{2} = 2; [~, B] = cellfun(@foo, x); f=@(c)foo(c); [A, B] = f(1); function [ab] = foo(x) a = x+1; b = x+2; end end 
+4
source share

This can be done using an array of cells as the only output of a function instead of a function with multiple outputs.

Define your function to return an array of cells (or create a helper function that calls a function with multiple outputs):

 function F = foo2(x) [a,b,c] = foo(x); F = {a, b, c}; end 

And then you can create a handle that calls your function and only get one of the cells from the cell array.

 f = @(x) cell(foo2(x)){2} % This selects the second output g = @(x) cell(foo2(x)){3} % This selects the third output 

This is almost what you asked for. You can even create a handle that returns the nth output

 f = @(x,n) cell(foo2(x)){n} 
0
source share

All Articles