Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 567
Tinashe Mutsvangwa Avatar asked Mar 07 '13 22:03

Tinashe Mutsvangwa


1 Answers

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?

like image 171
Sanjay Manohar Avatar answered Sep 22 '22 14:09

Sanjay Manohar