tags:

views:

88

answers:

1

I'm writing a wrapper to a function that takes varargin as its inputs. I want to preserve the function signature in the wrapper, but nesting varargin causes all the variable to be lumped together.

function inner(varargin) %#ok<VANUS>
% An existing function
disp(nargin)
end

function outer(varargin)
% My wrapper
inner(varargin);
end

outer('foo', 1:3, {})   % Uh-oh, this is 1

I need a way to unpack varargin in the outer function, so that I have a list of individual variables. There is a really nasty way to do this by constructing a string of the names of the variables to pass the inner, and calling eval.

function outer2(varargin) %#ok<VANUS>
% My wrapper, second attempt
inputstr = '';
for i = 1:nargin
   inputstr = [inputstr 'varargin{' num2str(i) '}']; %#ok<AGROW>
   if i < nargin
      inputstr = [inputstr ', ']; %#ok<AGROW>
   end
end    
eval(['inner(' inputstr ')']);
end

outer2('foo', 1:3, {})   % 3, as it should be

Can anyone think of a less hideous way of doing things, please?

+9  A: 

The call in inner in outer should instead be

inner(varargin{:})

In other words, expand varargin into the comma-separated list for the call to inner. Then you can avoid all the mess.

Loren
Thanks, that's very elegant.
Richie Cotton
Out of curiosity, is there an equivalent way of splitting arrays? Like a nicer version of `c = arrayfun(@(x) x, 1:3, 'UniformOutput', false); c{:}`.
Richie Cotton
Not sure it's nicer, but you can use variants of cell2mat perhaps. What's the matter with arrayfun, cryptic? You could also use a for loop if you preallocate the output. I don't think performance would be a big issue for reasonable size arrays.
Loren

related questions