Anonymous function with a variable-length argument list

£可爱£侵袭症+ 提交于 2020-01-12 13:52:01

问题


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?


回答1:


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



回答2:


  • va_arg in matlab called varargin here is the content of the link :

varargin is an input variable in a function definition statement that allows the function to accept any number of input arguments.

function varlist(varargin)
   fprintf('Number of arguments: %d\n',nargin);
   celldisp(varargin)

varlist(ones(3),'some text',pi)


Number of arguments: 3

varargin{1} =
     1     1     1
     1     1     1
     1     1     1

varargin{2} =
some text

varargin{3} =
    3.1416
  • define anonymous function as 2 of 4 outputs of m file function


来源:https://stackoverflow.com/questions/14614600/anonymous-function-with-a-variable-length-argument-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!