How to group rows with same column values?

2019-06-28 06:46发布

Given the matrix with coordinates in 3D space and values for two variables (say a and b) in two matrices I would like to merge rows for same points into a common matrix.

To clearly explain the matter, let's say we have matrices

A=[posX, posY, posZ, a]
and 
B=[posX, posY, posZ, b]

and would like to combine them into

AB = [posX, posY, posZ, a, b]

for example

A = [0 0 1 1; 0 1 0 4; 5 0 12 8];
B = [0 0 0 5; 0 1 0 3; 5 11 7 7];

would give

AB = [0 0 0 0 5; 0 0 1 1 0; 0 1 0 4 3; 5 0 12 8 0; 5 11 7 0 7];

In order to do that I first created

ATemp = [A, zeros(length(A,0)] 

and

BTemp = [B(:, [1 2 3]), zeros(length(B),1), B(:,4)]

and then tried to use functions accumarray and grpstats but haven't managed to form the AB matrix.

I would be very thankful if anyone suggested the way to get the desired matrix.

1条回答
ゆ 、 Hurt°
2楼-- · 2019-06-28 07:31
AB=union(A(:,1:3),B(:,1:3),'rows');
AB(ismember(AB,A(:,1:3),'rows'),4)=A(:,4);
AB(ismember(AB(:,1:3),B(:,1:3),'rows'),5)=B(:,4)

[edit] This solution is only valid if each (x,y,z)-point occurs only once in each matrix. If there are several, there is a dimension mismatch in the second line (and/or the third).

查看更多
登录 后发表回答