Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous function with a variable-length argument list

Can I create an anonymous function that accepts a variable number of arguments?

I have a struct array S with a certain field, say, bar, and I want to pass all the bar values to my anonymous function foo. Since the number of elements in struct S is unknown, foo must be able to accept a variable number of arguments.

The closest thing that I've been able to come up with is passing a cell array as the input argument list:

foo({arg1, arg2, arg3, ...})

and I'm invoking it with foo({S.bar}), but it looks very awkward.

Creating a special m-file just for that seems like an overkill. Any other ideas?

like image 671
Eitan T Avatar asked Jan 30 '13 21:01

Eitan T


1 Answers

Using varargin as the argument of the anonymous function, you can pass a variable number of inputs.

For example:

foo = @(varargin)fprintf('you provided %i arguments\n',length(varargin))

Usage

s(1:4) = struct('bar',1);
foo(s.bar)

you provided 4 arguments
like image 110
Jonas Avatar answered Nov 09 '22 16:11

Jonas