Eliminate all non unique rows from a matrix

25 次查看(过去 30 天)
Hello,
i've got a problem I don't really know how to solve efficiently:
I have a 2D pointcloud in matrix form: [x-values, y-values]. Matrix dimensions are nx2.
Now I want to make it so that every x- and every y-value only appear once in the entire matrix. So that for example if the 3rd point has x=2 every other point with x=2 is deleted and if the 1st point has y=7 every other point with y=7 is deleted. I could of course use unique(x) and unique(y) but then the results will most likely have different dimensions and also when I delete doublings of a certain x-value I need to delete the whole row so that the corresponding y-value is deleted, too and the other way round.
I hope my explanation was clear enough (not a native speaker) and someone can help me ;)

回答(2 个)

the cyclist
the cyclist 2017-6-18
What would the output be for
x = [2 6;
2 7;
3 7]
If you mean that you want to keep all the rows, because they are all unique, just do
unique(x,'rows')
If not, then you need to clarify the rule. Keep the first row with the 2? Or the first row with the 7?
  1 个评论
Yannick Roth
Yannick Roth 2017-6-18
the output should be [2 6; 3 7] or [2 7] for my program that doesn't matter. It's just important that every x- and every y-value appear only once. If I use unique(x, 'rows') - as far as I understand it - all values the entire row would have to be the same. So in your example no row would be deleted.

请先登录,再进行评论。


the cyclist
the cyclist 2017-6-18
Taking into account your comments in my other answer, I think this does what you want.
M = [2 6;
2 7;
3 7;
4 7];
% Remove non-unique first column values
[~,x_idx] = unique(M(:,1));
M2 = M(x_idx,:);
% Then remove non-unique second column values
[~,y_idx] = unique(M2(:,2));
M3 = M2(y_idx,:);
The output you need is in M3.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by