【问题标题】:I want to calculate the mean of two rows in matlab only if the first elemensts of thee two rows are equal [duplicate]只有当你两行的前元素相等时,我才想计算matlab中两行的平均值[重复]
【发布时间】:2012-09-26 06:05:47
【问题描述】:

可能重复:
I want to calculate the mean of two rows in matlab

我很抱歉重复自己,但我被困在一个点上。 我有一个 1028 x 18 矩阵,其中一些整行具有 NaN 值。所以我需要比较相邻行的前两个元素并仅在前两个元素相等时计算平均值。 D 是 1028 x 18 矩阵

 [m,n]=size(D);
    for i=1:m-1
    if D(i,1)==D(i+1,1)
    D=reshape(D, 2, m/2*n);
    D=(D(i,:)+D(i+1,:))/2;
    D=reshape(D, m/2, n);
     else
      end 
    end

【问题讨论】:

  • 你想对结果做什么?把它放在另一个矩阵中?在哪里?如果前 2 个元素 匹配,你想放什么?如果你回答问题并以代码的形式写下来,你可能会有答案。或者至少是一个足够详细的问题,有人可以回答。
  • 明确写出一个非常小的矩阵也可能会有所帮助,其中有些行是平均的,有些行不是平均的,然后显示函数的结果。
  • 为什么不再问同样的问题呢?第三次魅力。不要重复你自己。改为编辑第一个问题。

标签: matlab mean


【解决方案1】:

我没有matlab,但逻辑是这样的

for row=0,row++

    if ( m[row,1]  == m[row+1,1])
    {
        mean1 = mean(m[row]);
        mean2 = mean(m[row+1]);
        mean = mean(mean1,mean2);
    }

end for

/* 注意这个语法是不正确的,它只是给你一个想法 */

【讨论】:

  • 它为您提供了如何比较相邻两行的第一个元素并找到平均值的想法。或者你想要一个完整的解决方案:)
【解决方案2】:

您可以根据您的定义使用all(~diff(D(:,1:2)), 2) 对有效行进行逻辑索引,即第一列和第二列的元素,逐行差异为零。

然后您可以使用此索引返回整数行索引或全局行均值矩阵内的索引。

index_row = 1:1:size(D, 1); % linear row index 
index_valid = all(~diff(D(:,1:2)), 2); % valid rows (logical)

mean_matrix = (D(1:end-1,:) + D(2:end,:))/2; % matrix of all means

% matrix of valid mean rows only
mean_matrix_valid = mean_matrix(index_valid,:); % logical index 
% linear index of valid rows, i.e. the pairs indexed (i, i+1)
index_row_valid = index_row(index_valid); % valid rows (int) 

例如用

D = [1 2 3 4 5; 1 1 1 1 1; 1 2 4 4 4; 1 2 3 3 3; 2 2 2 2 2; 2 2 3 3 3];

>> D = 
     1     2     3     4     5
     1     1     1     1     1
     1     2     4     4     4
     1     2     3     3     3
     2     2     2     2     2
     2     2     3     3     3

你会得到,使用上面的

>> index_valid =

     0
     0
     1
     0
     1

>> index_row_valid =

 3     5

>> mean_matrix_valid =

    1.0000    2.0000    3.5000    3.5000    3.5000
    2.0000    2.0000    2.5000    2.5000    2.5000

分别是行 (3,4) 和 (5,6) 的均值。

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多