find common values of all rows of a matrix

三世轮回 提交于 2019-12-13 00:27:51

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/29783598/find-common-values-of-all-rows-of-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!