【问题标题】:Extract elements from matrix based on two rows and get their averages根据两行从矩阵中提取元素并获取它们的平均值
【发布时间】:2015-09-07 09:30:34
【问题描述】:

我在 matlab 中有一个 3 x n 数组。我想创建一个新的 4 x n 数组,其中包含第 1 行和第 2 行的所有唯一组合、每个组合的第三列的总和以及这些唯一组合存在的次数(以便稍后获得平均值)。

有没有一种有效的方法来做到这一点,而不使用两个嵌套的 for 循环?

编辑:所有三行都是数值(整数)。我使用 a,b,c,d 只是为了演示。

例如:

Unprocessed matrix:  
a b b d a a d d    
a c d d d a d d    
5 5 5 5 5 5 5 5

New matrix:
a  b  b  d  a   
a  c  d  d  d    
10 5  5  15 5    
2  1  1  3  1

【问题讨论】:

    标签: matlab matrix


    【解决方案1】:

    经典accumarray工作:

    A =  [1 2 2 4 1 1 4 4    
          1 3 4 4 4 1 4 4    
          5 5 5 5 5 5 5 5]
    
    A = A.' %'
    [u,~,subs] = unique(A(:,[1,2]),'rows')
    sums = accumarray(subs(:),A(:,3))
    occs = accumarray(subs(:),A(:,3),[],@numel)
    
    out = [u, (sums./occs), occs].'
    

    out =
    
         1     1     2     2     4
         1     4     3     4     4
         5     5     5     5     5
         2     1     1     1     3
    

    如果您坚持示例中的顺序,那么您需要 uniquestable accumarray'stable' 属性。

    【讨论】:

    • 像魅力一样工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2021-05-22
    • 2018-07-06
    相关资源
    最近更新 更多