Reputation: 127
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.
Upvotes: 5
Views: 2479
Reputation: 7026
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[ 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:
@(x)eig(x)
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?
Upvotes: 6
Reputation: 127
I see you cannot force a variable comma separated output list in Matlab. Pity. It would be useful. It seems I have to explicitly assign each output. This sucks since I do not know beforehand the number of outputs I will get.
Upvotes: -1