假设有 2 个向量 (i,j)
、A(10,1)
、B(10,1)
其中有从[1,10]
区间获取随机值。例如。
A = [1 6 1 10 1 7 1 9 3 6]
B = [7 2 3 5 6 8 7 9 10 2].
我有兴趣创建一个新向量,它将计算有多少个具有相同 i 索引的值出现。例如
1 and 7 ⇒ 2 occurrences
6 and 2 ⇒ 2 occurrences
1 and 3 ⇒ 1 occurrence
10 and 5 ⇒ 1 occurrence
1 and 6 ⇒ 1 occurrence
...
等等
这样,最终的数组/向量 C
就出现了,所有可能的对及其出现次数的计数大小都为 C(number_of_pairs,2)
。
最佳答案
使用accumarray
然后find
:
A = [1 6 1 10 1 7 1 9 3 6];
B = [7 2 3 5 6 8 7 9 10 2]; %// data
aa = accumarray([A(:) B(:)], 1); %// how many times each pair occurs
[ii jj vv] = find(aa);
C = [ii jj vv]; %// only pairs which occurr at least once
在您的示例中,这给出了
C =
6 2 2
1 3 1
10 5 1
1 6 1
1 7 2
7 8 1
9 9 1
3 10 1
或者aa
或vv
可能是您所需要的;我不确定您想要的输出是什么。
另一种可能的方法,灵感来自 @Rody's answer :
mat = [A(:) B(:)];
[bb ii jj] = unique(mat, 'rows');
C = [mat(ii,:) accumarray(jj,1)];
关于matlab - 查找一对值出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21677630/