【问题标题】:Is there a splat operator (or equivalent) in Matlab?Matlab 中是否有 splat 运算符(或等效运算符)?
【发布时间】:2012-02-08 04:20:35
【问题描述】:

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

像这样:

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 multidimensional-array operators matrix-indexing splat


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 2012-03-07
      • 2018-12-29
      • 2013-07-04
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 2014-08-29
      • 2010-09-27
      相关资源
      最近更新 更多