具有可变长度参数列表的匿名函数 [英] Anonymous function with a variable-length argument list

查看:83
本文介绍了具有可变长度参数列表的匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以创建一个接受可变数量参数的匿名函数吗?

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

我有一个带有特定字段(例如bar)的结构数组S,我想将所有bar值传递给我的匿名函数foo.由于struct S中的元素数量未知,因此foo必须能够接受可变数量的参数.

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, ...})

我正在用foo({S.bar})调用它,但是它看起来很尴尬.

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

为此创建一个特殊的m文件似乎是一个过大的选择.还有其他想法吗?

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

推荐答案

使用varargin作为匿名函数的参数,您可以传递可变数量的输入.

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

例如:

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

用法

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

you provided 4 arguments

这篇关于具有可变长度参数列表的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆