Amin Qassemi
Amin Qassemi

Reputation: 99

Find common elements between all columns of a matrix in matlab

I've a problem to find common elements between all columns of a matrix in MATLAB, I've tried to solve it my self, the basic problem is intersect function set intersect just between two matrices, so I wrote a code like this

A=randi(n,m);
B=struct();
for k=1:size(A,2)-1
    B.(['b' num2str(k)])=intersect(A(:,k),A(:,k+1));
end

unfortunately the problem isn't solve cause the dimension of A is unknown so we have same problem with B! thanks all.

Upvotes: 3

Views: 241

Answers (1)

Divakar
Divakar

Reputation: 221514

One vectorized approach using bsxfun -

unqA = unique(A)
out = unqA(all(any(bsxfun(@eq,A,permute(unqA,[2,3,1])),1),2))

Sample run -

A =
     8     5     6     4     8
     4     6     7     5     9
     9     4     4     7     5
     9     4     9     5     6
     9     9     7     9     6
     9     5     9     4     8
     8     5     6     9     8
     7     5     6     7     4
out =
     4
     9

Upvotes: 1

Related Questions