Capture all possible outputs based on variable number of inputs.
capture, matlab, variables
Solution
I know this is late, but I think this is what you want:
function [varargout] = myfun(f, varargin)
% apply f to args, and return all its outputs
[ x{1:nargout(f)} ] = f(varargin{:}); % capture all outputs into a cell array
varargout = x; % x{:} now contains the outputs of f
The insight here is that
- `NARGOUT` can operate on functions and returns their maximum number of outputs
- using `[ X{1:2} ] = ...`on the left hand side when X is undefined, is equivalent to doing `[ X{1} X{2} ] = ...`, and can capture 2 separate outputs into individual variables.
Two points to note:
- this works for anonymous functions too! e.g. `@(x)eig(x)`
- it won't work for functions that use `varargout`, i.e. functions with truly variable numbers of outputs. If this is the case then there should be a way to calculate how many outputs you are going to have, e.g. using `nargin`.
PS I learnt this from @gnovice, If a MATLAB function returns a variable number of values, how can I get all of them as a cell array?
Problem
I would like Matlab to return all the outputs from a variable input function. For instance, [varargout]=cpd_intersect(varargin{:}); This only returns the last output but I know the function is defined to give multiple outputs. Instead of defining dummy variables A, B , C etc in [A,B,C...]=pd_intersect(varargin{:}). I would like something like a cell to store all the output values based on the input number of values. I hope this makes sense. Many thanks in advance.