A.R*_*ner 2 indexing matlab matrix
我有72x7双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
...
3 87 24 43 71 3 41
5 64 8 66 75 98 1
Run Code Online (Sandbox Code Playgroud)
我感兴趣的两列是1和6.让我们把在第1列的值米和在第6列的值Ñ.m的范围是1-6,n的范围是1到3或4.我想计算具有m和n的特定组合的行数.我们称这个值为x.例如,在该示例中,如果m = 1并且n = 1,则x将是2,因为存在两行,其中m = 1并且n = 1(行1和2).如果m = 2的 AND n = 3时,X是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
Run Code Online (Sandbox Code Playgroud)
我尝试了数字和独特的功能,但都没有给我正确的答案.有人能帮助我吗?
谢谢,
亚历克斯
一种方法——
%// 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]
Run Code Online (Sandbox Code Playgroud)
因此,当 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 ]
Run Code Online (Sandbox Code Playgroud)
我们将输出为 -
out =
1 1 2
2 3 3
Run Code Online (Sandbox Code Playgroud)
因此,在输出中,第一列代表m,第二n列将是,最后一列将是预期的计数。
假设正整数值,这用于sparse产生期望的结果.输出格式与Divakar的答案一样:
[ii, jj, kk] = find(sparse(P(:,1), P(:,6), 1));
result = [ii jj kk];
Run Code Online (Sandbox Code Playgroud)