matlab - Matlab 中是否有 splat 运算符(或等效运算符)?

标签 matlab multidimensional-array operators matrix-indexing splat

如果我有一个数组(直到运行时长度未知),有没有办法调用一个函数,将数组的每个元素作为单独的参数?

像这样:

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 之一之外,这可能是您在示例中最接近“运算符”形式的东西。 (如图所示 herehere )以便它从标准数组生成一个逗号分隔的列表,或者创建您自己的类来存储您的索引并定义现有运算符如何对其进行操作(对于胆小的人来说这两个选项都不是!)。

对于索引任意 N 维数组的具体示例,您还可以使用 sub2ind 从下标索引计算线性索引函数(详见 herehere ),但你最终可能会比我上面的逗号分隔列表解决方案做更多的工作。另一种选择是 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/

相关文章:

Matlab问题: fixing the scale of Y axis in hist

arrays - 如何通过将函数应用于每个元素的索引来在 MATLAB 中创建数组?

c - 如何使用可变长度的二维数组作为函数的参数

function - 使用百分号作为前缀运算符名称的一部分

matlab - 如何删除 MATLAB 中元胞数组中的零条目?

php - 将多维数组数据插入MySQL DB

php - 在php中将多维数组中的数据插入MySQL

scala - Scala 中的 += 运算符

javascript - 使用 Modulus 为 jquery 循环自定义寻呼机返回

arrays - 提取数组中大于零的值集的索引