I have a function that returns 2 things (e.g. a function value and a jacobian).
function [f_val, J_val] = f(x)
f_val = x;
J_val = [1 0; 0 1];%.....
end
What I want is a function to extract the first or the second output parameter. Clearly I can go [f_sol; J_sol] = f([1 1])
and then extract the appropriate value, but I need to do this inside of an anonymous function where that sort of assignment isn't possible.
Ugly Solution One can create the following function,
function out = output_part(i, f, varargin) %This calls it here, but I would rather not
[all_out{1:nargout(f)}] = f(varargin{:});
out = all_out{i};
end
And then call something like: output_part(2, @f, [ 0 1])
serving my purpose, but it is ugly. Better syntax would be output_part(2, f([0,1]))
but I can't figure out how to write this. What we would really need is a way to have the multiple variable outputs of a function end up as variable inputs of the calling function. I can't figure out if that is possible.
Multiple Output Arguments:
This is not duplicate of How can I index a MATLAB array returned by a function without first assigning it to a local variable? This is of the same nature, but multiple arguments are handled differently. Something a little more related is the kthout
function in How to elegantly ignore some return values of a MATLAB function? which does something like my output_part
above.
The problem here just to be that you cannot easily chain multiple outputs of a function into the multiple inputs of another function through function composition.