如果我有一个数组(直到运行时长度未知),有没有办法调用一个函数,将数组的每个元素作为单独的参数?
像这样:
foo = @(varargin) sum(cell2mat(varargin));
bar = [3,4,5];
foo(*bar) == foo(3,4,5)
上下文:我有一个 n
-d 数组 Q
的索引列表。我想要的是 Q(a,b,:)
,但我只有 [a,b]
。因为我不知道 n
,所以我不能只对索引进行硬编码。
最佳答案
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 )以便它从标准数组生成一个逗号分隔的列表,或者创建您自己的类来存储您的索引并定义现有运算符如何对其进行操作(对于胆小的人来说这两个选项都不是!)。
对于索引任意 N 维数组的具体示例,您还可以使用 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)
关于matlab - Matlab 中是否有 splat 运算符(或等效运算符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8825574/