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

标签 matlab matrix indexing

我有一个名为 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。我想计算有多少行具有 m< 的特定组合/strong> 和 n。我们称此值为 x。例如,在此示例中,如果 m=1n=1x 将为 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,最后一列代表预期计数。

关于matlab - 计算矩阵中值的唯一组合数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29567466/

相关文章:

r - 使用空索引索引列表

python - 使用索引数组索引多维 Numpy 数组

matlab - 如果 csvread 失败则跳过文件 Matlab

matlab - 音频信号中的峰值检测

matlab - 计算区域内所有点之间的距离

python - python3.4 的 numpy 矩阵字符串

matlab - 如何在 Matlab 中增量训练神经网络?

matlab - 在 Matlab 中查找 pcolor 中的轮廓/边缘

r - 矩阵乘法-不合格矩阵的宽松定义

Javascript 数组拼接而不改变索引