【问题标题】:Find the mean of a sub matrix if the first column of the matrix provides the index values如果矩阵的第一列提供索引值,则求子矩阵的均值
【发布时间】:2014-06-23 04:14:09
【问题描述】:

对于给定的矩阵Z,并假设第一列是索引值,是否可以根据第一列Z(:,1)中的索引值找到Z(:,2:3)的平均值。

Z  =  [1    3    4
       2    7    8
       1    3    9
       3    4    4
       1    5    7]

那么我如何循环 Z 以找到索引值为 1 的相应行的平均值(在第一列中),即找到 Z1 的平均值

Z1  =    3  4
         3  9
         5  7

请任何人帮忙解释一下如何做到这一点?

【问题讨论】:

    标签: matlab matrix octave mean


    【解决方案1】:

    这应该可以解决问题:

    mean(mean(Z(Z(:,1)==1,2:3)))
    

    【讨论】:

    • 非常感谢盖欧!我实际上设法在没有第二种方法的情况下解决了我的问题。
    【解决方案2】:

    怎么样:

    mean([accumarray(Z(:,1), Z(:,2),[],@mean), accumarray(Z(:,1), Z(:,3),[],@mean)]')'
    

    它为您提供与每个数字对应的平均值。即结果的第一行是对应于1的行的平均值,第二行是2

    【讨论】:

    • 感谢教我 'accumarray()',这是一个非常好的解决方案
    【解决方案3】:

    Bsxfun 方法-

    Zc = [Z(:,1) mean(Z(:,[2 3]),2)]
    
    ind1 = bsxfun(@eq,Zc(:,1),min(Zc(:,1)):max(Zc(:,1)))
    mean_values = sum(bsxfun(@times,ind1,Zc(:,2)))./sum(ind1,1)
    

    输出 -

    mean_values =
        5.1667    7.5000    4.0000
    

    【讨论】:

      【解决方案4】:

      要一次性对第 1 列中的每个索引执行此操作:

      >> accumarray(repmat(Z(:,1),size(Z,2)-1,1), reshape(Z(:,2:3),[],1), [], @mean)
      ans =
          5.1667
          7.5000
          4.0000
      

      【讨论】:

        猜你喜欢
        • 2013-10-15
        • 1970-01-01
        • 1970-01-01
        • 2012-06-22
        • 2018-09-23
        • 2018-05-12
        • 1970-01-01
        • 1970-01-01
        • 2018-03-16
        相关资源
        最近更新 更多