查找矩阵所有行的公共值 [英] 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?
推荐答案
使用 unique
,然后使用bsxfun
:
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);
这应该很快,但可能会占用大量内存,因为它会生成大小为 m x n x p 的3D数组,其中A
是 m x n ,而 p 是A
的唯一值的数量.即使行中可以包含重复的元素,它仍然有效.
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);
这篇关于查找矩阵所有行的公共值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!