How to remove duplicates from a matrix without using unique?

조회 수: 2 (최근 30일)
jeff417
jeff417 2016년 4월 14일
댓글: Eduardo Negredo Martin 2021년 10월 15일
I have to be able to remove all duplicates from each column of a matrix A = [1,2,3;1,3,3;4,2,1], while also not using unique and not changing the order.
I got the code to work for a single column, I'm just not sure how to do it for a matrix.
z = length(A);
Ab = zeros(size(A));
for i = 1:(z-1)
Ab(i) = sum(A(i) == A(i+1:end));
end
AA = A(Ab == 0);
end
  댓글 수: 5
Jos (10584)
Jos (10584) 2016년 4월 14일
and why can't you use unique ...

댓글을 달려면 로그인하십시오.

답변 (3개)

Kuifeng
Kuifeng 2016년 4월 14일
% use the function ismember for each column, and it would help
doc ismember
  댓글 수: 3
Kuifeng
Kuifeng 2016년 4월 14일
then the following is ok based on your available column code,
[rows cols] = size(A);
Ab = zeros(rows, cols);
for j = 1: cols
for i = 1:rows-1
Ab(i, j) = sum(A(i,j) == A(i+1:end, j));
end
end
A(Ab == 1) =nan;
Jan
Jan 2016년 4월 14일
Kuifeng's suggestion contains the builtin functions: size, subsref, subsasgn, zeros, for, colon, eq, end, nan.

댓글을 달려면 로그인하십시오.


Andrei Bobrov
Andrei Bobrov 2016년 4월 14일
편집: Andrei Bobrov 2016년 4월 14일
A = [1,2,3;1,3,3;4,2,1];
[a,ii] = sort(A);
a([false(1,size(a,2));diff(a)==0]) = nan;
[~,i1] = sort(ii);
out = a(sub2ind(size(A),i1,ones(size(A,1),1)*(1:size(A,2))));

Jos (10584)
Jos (10584) 2016년 4월 14일
I do not see any reason why you can't use unique
A = randi(5,5,10) % some data
C = arrayfun(@(k) unique(A(:,k),'stable'),1:size(A,2),'un',0)
C{k} now holds the unique values of column k of A in preserved order ...
  댓글 수: 4
Adam
Adam 2016년 4월 14일
편집: Adam 2016년 4월 14일
These questions do always seem odd to me too. Not using builtin functions makes using Matlab itself kind of pointless. If you come to use Matlab in a real work environment your employers would expect you to make use of every helpful function available to you.
It also begs the question of what counts as a builtin function.
length, zero and sum in the author's original answer are all builtin, as are numerous hidden function such as subsref that get called when you do almost anything with arrays!
But I agree with Guillaume that the only purpose (though even then a questionable one) of being asked to not use builtin functions is to work out your own method!
Eduardo Negredo Martin
Eduardo Negredo Martin 2021년 10월 15일
When I use the function 'unique', it changes the order to smallest to largest, which messes up the matrix fpr me.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by