如何在同一矩阵中将一行的元素与其他行的元素进行比较 [英] How do I compare elements of one row with every other row in the same matrix
问题描述
我有矩阵:
a = [ 1 2 3 4;
2 4 5 6;
4 6 8 9]
,我想将每一行与其他两行一一比较.如果他们共享相同的密钥,那么结果将告诉他们拥有一个公共密钥.
and I want to compare every row with every other two rows one by one. If they share the same key then the result will tell they have a common key.
推荐答案
这是一个解决方案(可以推广到比问题中的样本更大的矩阵):
Here's one solution (which is generalizable to larger matrices than the sample in the question):
comparisons = nchoosek(1:size(a,1),2);
N = size(comparisons,1);
keys = cell(N,1);
for i = 1:N
keys{i} = intersect(a(comparisons(i,1),:),a(comparisons(i,2),:));
end
函数 NCHOOSEK 用于生成所有行比较的 unique 组合.对于问题中的矩阵a
,您将得到comparisons = [1 2; 1 3; 2 3]
,这意味着我们需要比较行1和2,然后比较1和3,最后是2和3.keys
是 INTERSECT 用于查找通用值(即键).对于问题中给出的矩阵a
,您将获得keys = {[2 4], 4, [4 6]}
.
The function NCHOOSEK is used to generate all of the unique combinations of row comparisons. For the matrix a
in your question, you will get comparisons = [1 2; 1 3; 2 3]
, meaning that we will need to compare rows 1 and 2, then 1 and 3, and finally 2 and 3. keys
is a cell array that stores the results of each comparison. For each comparison, the function INTERSECT is used to find the common values (i.e. keys). For the matrix a
given in the question, you will get keys = {[2 4], 4, [4 6]}
.
这篇关于如何在同一矩阵中将一行的元素与其他行的元素进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!