当第1列和第2列具有相同的数字时,平均第3列

时间:2013-08-02 19:14:45

标签: matlab matrix average

让我们简单一点,假设我在matlab中有一个10x3矩阵。每行前两列中的数字表示x和y(位置),第3列中的数字表示相应的值。例如,[1 4 12]表示x = 1和y = 4中的函数值等于12.我在不同的行中也有相同的x和y,我想平均具有相同x,y的值。并用平均值替换所有这些。

例如:

A = [1 4 12 
     1 4 14
     1 4 10
     1 5 5
     1 5 7];

我想要

B = [1 4 12
     1 5 6] 

我非常感谢你的帮助 谢谢 阿里

4 个答案:

答案 0 :(得分:2)

喜欢这个吗?

A = [1 4 12;1 4 14;1 4 10; 1 5 5;1 5 7];
[x,y] = consolidator(A(:,1:2),A(:,3),@mean);
B = [x,y]
B =
     1     4    12
     1     5     6

Consolidator在文件交换中。

答案 1 :(得分:1)

使用内置功能:

sparsemean = accumarray(A(:,1:2), A(:,3).', [], @mean, 0, true);
[i,j,v] = find(sparsemean);
B = [i.' j.' v.'];

答案 2 :(得分:0)

A = [1 4 12;1 4 14;1 4 10; 1 5 5;1 5 7]; %your example data
B = unique(A(:, 1:2), 'rows'); %find the unique xy pairs
C = nan(length(B), 1);

% calculate means
for ii = 1:length(B)
    C(ii) = mean(A(A(:, 1) == B(ii, 1) & A(:, 2) == B(ii, 2), 3));
end

C =
    12
     6

for循环中的步骤使用逻辑索引来查找与循环中当前xy对匹配的行的平均值。

答案 3 :(得分:0)

使用unique获取唯一行并使用返回的索引数组来查找应该平均的数组,并要求accumarray执行平均部分:

[C,~,J]=unique(A(:,1:2), 'rows');
B=[C, accumarray(J,A(:,3),[],@mean)];

为您的例子

>> [C,~,J]=unique(A(:,1:2), 'rows')
C =
     1     4
     1     5
J =
     1
     1
     1
     2
     2

C包含唯一的行,J显示原始矩阵中的哪些行与C中的行相对应

>> accumarray(J,A(:,3),[],@mean)
ans =
    12
     6

返回所需的平均值和

>> B=[C, accumarray(J,A(:,3),[],@mean)]
B =
     1     4    12
     1     5     6

就是答案。

相关问题