Matlab: defining a function handle catching second returned value of a function

function-handle, matlab

Solution

From the documentation of `cellfun`:

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

So yes, `cellfun` can use a multi-output function and in this case it simply returns a number of outputs. If you want to use the second one only, you can use `~` to ignore the first one. The same goes for multiple outputs of anonymous functions - they will be returned if you specify multiple 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 [a b] = foo(x)
        a = x+1;
        b = x+2;
    end
end

Problem

Say that I have a function `foo` defined as ``` [a b] = foo(c ). ``` If I consider a function handle ``` f = @(c)foo(c) ``` to be used e.g. in a `cellfun` call, what I get is an `f` behaving equivalently to a `foo` defined like ``` a = foo(c) ``` i.e., the returned value `b` gets lost. Therefore, when such an `f` is put in a `cellfun` call, the output cell will have just the `a`s and will miss the `b`s (which I currently care about). Visually ``` cellfun(f,input) [a(input{1})] ? [a(input{2})] ? .... b gets killed along the way ``` Question: how to define a function handle to `foo` which catches just the `b`s? i.e. giving a behavior analogous to a definition of `foo` like ``` b = foo(c) ``` i.e.^2, wasting the `a`s. Moreover, is it possible to (efficiently) catch both `a` and `b` in a unique `cellfun` call?

Original source

Related problems