I am looking for non-repeated rows in a matrix.
Assume:
A =
8 1
2 2
2 2
2 2
2 2
3 6
5 7
5 7
I would like to get "B" which is:
B=
8 1
3 6
Please mind C=unique(A,'rows') will give us unique rows of "A" which include repeated and non-repeated arrays and only remove repetitious rows. It means:
C =
2 2
3 6
5 7
8 1
"C" is not the one that I am looking for.
Any help would be greatly appreciated!
Use the second and third outputs of unique
as follows:
[~, ii, jj] = unique(A,'rows');
kk = find(histc(jj,unique(jj))==1);
B = A(sort(ii(kk)),:);
Or use this more direct bsxfun
-based approach:
B = A(sum(squeeze(all(bsxfun(@eq, A.', permute(A, [2 3 1])))))==1,:);
These two approaches work in quite generally: A
may have any number of columns, and may contain non-integer values.
If A
always has two columns and contains only integer values, you can also do it with accumarray
, using the sparse option (sixth input argument) to save memory in case of large values:
[ii jj] = find(accumarray(A, 1, [], @sum, 0, true)==1);
B = [ii jj];
Or you can use sparse
instead of accumarray
:
[ii jj] = find(sparse(A(:,1),A(:,2),1)==1);
B = [ii jj];