如何根据列值计算矩阵均值 [英] How to calculate mean of matrix based on column value

查看:370
本文介绍了如何根据列值计算矩阵均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有N * 4暗的B矩阵.我想根据最后一列的值计算矩阵的平均值.最后一列的重复值在1到3的范围内.我想计算最后一列具有相同值的所有行的均值. 我正在使用以下命令:

I have B matrix of N*4 dim. I want calculate the mean of the matrix based on last column values. Last column has repeated values in the range of 1 to 3. I want to calculate the mean of all rows whose last column have same value. I am using this command:

l(it:,)=mean(B(i,:)) 

其中it在循环中的范围是1到3,并且i具有最后一列为1的行的所有索引.当我运行此代码时,得到Sub scripted assignment dimension mismatch error.谁能指出命令中有什么问题吗?

where it ranges from 1 to 3 in the loop and i has all the indices of rows whose last column=1.When I run this code I get Sub scripted assignment dimension mismatch error. Can anyone point out what is wrong in the command?

推荐答案

请考虑以下示例数据:

B = [ 0.4000    0.3000    0.2000    1.0000
      0.3000    0.2000    0.1000    2.0000
      0.7000    0.8000    0.6000    1.0000
      0.3000    0.4000    0.8000    2.0000
      0.7000    0.5000    0.5000    3.0000
      0.1000    0.3000    0.9000    3.0000
      0.6000    0.4000    0.5000    1.0000 ];

两种可能的方法:

  1. 使用逻辑索引 :

result = NaN(3,3);
for k = 1:3
    result(k,:) = mean(B(B(:,4)==k,1:3));
end

  • 使用 accumarray :

    result = NaN(3,3);
    for k = 1:3
        result(:,k) = accumarray(B(:,4), B(:,k), [], @mean, NaN);
    end
    

  • 使用示例数据,以上任何一项都给出

    With the example data, either of the above gives

    result =
        0.5667    0.5000    0.4333
        0.3000    0.3000    0.4500
        0.4000    0.4000    0.7000
    

    这篇关于如何根据列值计算矩阵均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆