Tinashe Mutsvangwa
Tinashe Mutsvangwa

Reputation: 127

Capture all possible outputs based on variable number of inputs.

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

Answers (3)

Sanjay Manohar
Sanjay Manohar

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

  1. NARGOUT can operate on functions and returns their maximum number of outputs
  2. 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:

  1. this works for anonymous functions too! e.g. @(x)eig(x)
  2. 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?

Upvotes: 6

Tinashe Mutsvangwa
Tinashe Mutsvangwa

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

Lolo
Lolo

Reputation: 4159

You can do this by returning a cell array

Upvotes: 0

Related Questions