【问题标题】:BetaCV in matlabmatlab中的BetaCV
【发布时间】:2017-09-22 09:44:58
【问题描述】:

我有一个 2 列 20 行的矩阵索引。

indices = 
[1 2; 
2 3; 
2 1; 
... ]

还有一个 4 行 4 列的第二个矩阵 distMat,我想找到 distMat 中位于每行索引[]中给定位置的元素的总和[]

distMat = 
[1 3 1 5
 2 2 4 2
 3 8 3 7
 3 8 3 7]

因为索引行是 1 2, 2 3, 3 1 所以应该检索并添加该位置的元素

所以我写了

result = sum(distMat[indices])

我收到语法错误。那么如何解决这个问题

【问题讨论】:

    标签: arrays matlab matrix octave


    【解决方案1】:

    另一种方法:使用sparse 构建一个logical index 来选择要求和的值:

    indices = [1 2; 2 3; 2 1];
    distMat = [1 3 1 5; 2 2 4 2; 3 8 3 7; 3 8 3 7];
    result = sum(distMat((sparse(indices(:,1), indices(:,2), true, size(distMat,1), size(distMat,2)))));
    

    这个works in Octave 也是。

    【讨论】:

      【解决方案2】:

      一种方法是获取线性索引,然后简单地索引和求和,就像你最后所做的一样 -

      idx = sub2ind(size(distMat), indices(:,1), indices(:,2));
      out = sum(distMat(idx))
      

      示例运行 -

      >> indices
      indices =
           1     2
           2     3
           2     1
      >> distMat
      distMat =
           1     3     1     5
           2     2     4     2
           3     8     3     7
           3     8     3     7
      >> idx = sub2ind(size(distMat), indices(:,1), indices(:,2));
      >> distMat(idx)
      ans =
           3
           4
           2
      >> sum(distMat(idx))
      ans =
           9
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 2011-01-04
        • 2016-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        相关资源
        最近更新 更多