Wednesday, May 13, 2009

Matlab: matrix indexing; find duplicate entries in a matrix and replace them with average

OP here.

Q:
I've got a matrix of integer values with three columns (X,Y,Z) and about 10k rows.
X and Y are in range 0..1000 and Z is in the range of 0..200.

In this matrix, there are some pairs of (X,Y) that occur more than once, but with different Z values. Now I want to remove these duplicates and replace all of them with (X,Y,mean of Z).

A:


[u,id1,id2] = unique(A(:,1:2),'rows');
B = [u,accumarray(id2,A(:,3))./accumarray(id2,1)];
% or accumarray(id2,A(:,3),[],@mean) but this is much slower.



Speed test:

% A = [round(rand(10000,2)*1000),round(rand(10000,1))*200];
Elapsed time is 0.005959 seconds.

No comments: