如何根据其他列的值查找特定值的平均值

时间:2017-12-26 11:36:52

标签: matlab matrix

我有一个如下矩阵。

2   1   0.020000000
2   1   0.020000000
2   1   0.020000000
2   1   0.020000000
2   2   0.434776340
2   2   0.392582120
2   2   0.549031660
2   3   0.0306320700000000
2   3   0.0336107500000000
3   1   0.0200000000000000
3   1   0.0200000000000000
3   1   0.0200000000000000
3   1   0.0200000000000000
3   1   0.0200000000000000
3   2   0.301534290000000
3   2   0.381151280000000
3   2   0.227146390000000
3   2   0.402937460000000
3   3   0.0773929900000000
3   3   0.0220243800000000
3   3   0.0859914800000000

我想检查第一列值是否为2然后检查下一列,如果其值为1,则计算第3列中所有值的平均值,因此它将如下所示:

第3列的平均值并将其放在不同的矩阵中。

    2   1   0.020000000
    2   1   0.020000000
    2   1   0.020000000
    2   1   0.020000000

然后尝试这个过程2 2 2,3 3 3等等。

第二列的值为1,2或3,但第一列的值在2-5000的范围内。   我试过这样但但它没有正常工作:

 [ii,jj]=find((S(:,2)==1)); //S is the matrix i mentioned earlier
      out=S(ii,[1,3]);
      for i=2:3
          if out(:,1)==i
              Mean(i) = mean (out(i,2));
          end
      end

谢谢!

2 个答案:

答案 0 :(得分:2)

使用uniqueaccumarray功能:

[unique_vals, ~, idx3]=unique(a(:,[1 2]),'rows'); % find unique combinations
means = accumarray(idx3, a(:,3),[],@mean); % find means
result = [unique_vals means]; % join groups and their means

答案 1 :(得分:1)

我不确定我是否理解这个问题,因为你写的是你想要计算第三列中值的平均值,而且还要制作一个子矩阵。

现在我假设您要计算第三列中前两列中有2 1的所有值的平均值。代码看起来像这样

mean21 = mean(S(S(:,1) == 2 & S(:,2) == 1,3))

首先计算一个布尔列,其中col1 == 2 AND col2 == 1 (S(:,1) == 2 & S(:,2) == 1),然后检索col3的相应值。

如果您自动希望对任意大的矩阵执行此操作,以下将是一个解决方案

for c1 = unique(S(:,2))'
    for c2 = unique(S(:,2))'
        mean_val(c1,c2) = mean(S(S(:,1) == c1 & S(:,2) == c2,3));
    end
end

但是,如果组合c1,c2不存在,这将为您提供NaN。

相关问题