计算矩阵中值的唯一组合数

Count number of unique combinations of values within a matrix

我有一个叫做 P 的 72x7 double,像这样:

1 45 2  61 7 1 11  
1 32 6  23 64 1 32  
2 55 32 25 90 3 24  
2 45 6  6 16 3 1  
2 45 4  17 20 3 1  
...
3 87 24 43 71 3 41  
5 64 8  66 75 98 1  

我感兴趣的两列是 16。让我们调用第 1 列中的值 m 和第 6 列中的值 nm 范围从 1-6,n 范围从 1 到 3 或 4。我想计算有多少行具有特定组合mn。我们称这个值为 x。例如,在此示例中,如果 m=1n=1,则 x 将为 2,因为有两行 m=1 AND n=1(第 1 行和第 2 行)。如果 m=2 AND n=3x 将为 3(第 3、4 行和5). 我打算做一个循环,像这样:

for m=1:6
   for n=1:a % a could be either 3 or 4
   x = (operation done here)
   end
end

我尝试了 numel 和 unique 函数,但都没有给我正确的答案。有人可以帮助我吗?

谢谢,

亚历克斯

一种方法-

%// Get columns 1 and 6 from input matrix, P
P16 = P(:,[1 6])

%// Get unique row combinations and their IDs
[unqrows,~,idx] = unique(P16,'rows')

%// Get the counts for each combination
counts = accumarray(idx(:),1) %// Or histc(idx,1:max(idx))

%// Present the output
out = [unqrows counts]

因此,P为-

P = [1 45 2  61 7 1 11
    1 32 6  23 64 1 32
    2 55 32 25 90 3 24
    2 45 6  6 16 3 1
    2 45 4  17 20 3 1 ]

我们将输出为 -

out =
     1     1     2
     2     3     3

因此,在输出中,第一列代表 m,第二列代表 n,最后一列代表预期计数。

假设 正整数 值,这使用 sparse to produce the desired result. The output format is as in :

[ii, jj, kk] = find(sparse(P(:,1), P(:,6), 1));
result = [ii jj kk];