如果我有一个数组(在运行时之前长度未知),有没有办法调用一个函数,并将数组的每个元素作为一个单独的参数?
像这样:
foo = @(varargin) sum(cell2mat(varargin));
bar = [3,4,5];
foo(*bar) == foo(3,4,5)
上下文:我有一个n
- d数组的索引列表,Q
。我想要的是Q(a,b,:)
,但我只有[a,b]
。由于我不知道n
,我不能只对索引进行硬编码。
答案 0 :(得分:10)
MATLAB中没有运算符可以做到这一点。但是,如果您的索引(例如示例中的bar
)存储在cell array中,那么您可以这样做:
bar = {3,4,5}; %# Cell array instead of standard array
foo(bar{:}); %# Pass the contents of each cell as a separate argument
{:}
从单元格数组创建comma-separated list。除了覆盖existing operators之一(图示为here和here)之外,这可能是您在示例中最接近“运算符”表单的内容,以便生成标准数组中以逗号分隔的列表,或创建自己的类来存储索引并定义现有运算符如何操作(对于胆小的人来说都不是选项!)。
对于索引任意ND数组的特定示例,您还可以使用sub2ind
函数(详细here和here)从您的下标索引计算线性索引,但你可能最终会做比上面我逗号分隔列表解决方案更多的工作。另一种选择是compute the linear index yourself,它将回避converting to a cell array并仅使用矩阵/向量运算。这是一个例子:
% Precompute these somewhere:
scale = cumprod(size(Q)).'; %'
scale = [1; scale(1:end-1)];
shift = [0 ones(1, ndims(Q)-1)];
% Then compute a linear index like this:
indices = [3 4 5];
linearIndex = (indices-shift)*scale;
Q(linearIndex) % Equivalent to Q(3,4,5)