teaLeef
teaLeef

Reputation: 1989

Filtering a matrix by unique column elements

M is a matrix: M = [X Y Z] where X, Y and Z are column vectors.

What is the easiest way to filter M so that: 1- No element is repeated per column 2- The order of the rows remain (if an element appears twice in a column, then I want to delete the entire row where it appears the second time)

e.g:

M = [1 2 4; 
1 3 5;
2 3 9]

would become

Mf = [1 2 4;
2 3 9]

I tried to use [u,~,ind] = unique(M,'rows') to have the elements for which one element in a column is repeated, but this function deals with the entire row (if only one element of the row is repeated, then the row is unique)

Upvotes: 0

Views: 94

Answers (1)

David
David

Reputation: 8459

Here is a quick and dirty solution, should be fine as long as you M isn't too big. I've tested it on a few matrices and it seems to work as intended.

count=1;
for i=1:length(M(1,:))^2
    [~,IA,~]=unique(M(:,count),'first');
    if length(IA)~=length(M(:,1))
        M=M(IA,:);
        count=count-1;
    end
    count=count+1;
    if count>length(M(:,1))
        break
    end
end
M

Upvotes: 2

Related Questions