Angelababy
Angelababy

Reputation: 243

find common values of all rows of a matrix

I have a random generated matrix

A =[ 0.7015 -1.577  -1.333  0.022   -0.5    -2.00   -0.034 -0.714
     -2.05   -0.5   1.12    -0.26   -0.97   0.96    -0.79   1.35
     -0.353  0.28   -0.5       -1.75    -1.15   0.52    1.018   -0.22
     -0.8   0.033   -0.29   -0.28   -0.5    -0.02   -0.13   -0.58 ]

I want to find the common values of all rows.Each row has no duplicated elements. Can anyone give me a help?

Upvotes: 1

Views: 694

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Get a vector of unique values with unique, and then compare each element of A with each unique value using bsxfun:

u = unique(A);
m = squeeze(all(any(bsxfun(@eq, A, permute(u, [2 3 1])),2),1));
result = u(m);

This should be fast, but may be memory-hungry, as it generates a 3D array of size mxnxp, where A is mxn and p is the number of unique values of A. It works even if a row can contains duplicated elements.


Exploiting the fact that each row has no duplicated elements, you can use a possibly more memory-eficient approach with accumarray:

[u, ~, w] = unique(A);
m = accumarray(w,1)==size(A,1);
result = u(m);

Upvotes: 2

Related Questions