如何将具有相同列值的行分组? [英] How to group rows with same column values?

查看:96
本文介绍了如何将具有相同列值的行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出具有3D空间中的坐标以及两个矩阵中两个变量(例如a和b)的值的矩阵,我想将相同点的行合并到一个公共矩阵中.

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]

,并希望将它们合并为

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

例如

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];

愿意给

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];

为此,我首先创建了

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

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

,然后尝试使用函数accumarraygrpstats,但没有设法形成AB矩阵.

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.

推荐答案

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]仅当每个(x,y,z)点在每个矩阵中仅出现一次时,此解决方案才有效.如果有多个,则第二行(和/或第三行)的尺寸不匹配.

[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).

这篇关于如何将具有相同列值的行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆