MATLAB:计算整数向量中2个数字组合的唯一#的最快方法

Ber*_* U. 6 matlab

给定一个整数向量,例如:

X = [1 2 3 4 5 1 2]
Run Code Online (Sandbox Code Playgroud)

我想找到一种非常快速的方法来计算具有2个元素的独特组合的数量.

在这种情况下,两个数字组合是:

[1 2] (occurs twice)
[2 3] (occurs once) 
[3 4] (occurs once) 
[4 5] (occurs once) 
[5 1] (occurs once) 
Run Code Online (Sandbox Code Playgroud)

按照目前的情况,我目前在MATLAB中这样做如下

X = [1 2 3 4 5 1 2];
N = length(X)
X_max = max(X);
COUNTS = nan(X_max); %store as a X_max x X_max matrix

for i = 1:X_max

    first_number_indices   = find(X==1)
    second_number_indices = first_number_indices + 1;
    second_number_indices(second_number_indices>N) = [] %just in case last entry = 1
    second_number_vals = X(second_number_indices);

   for j = 1:X_max
        COUNTS(i,j) = sum(second_number_vals==j)
   end
end
Run Code Online (Sandbox Code Playgroud)

这样做有更快/更聪明的方法吗?

Amr*_*mro 12

这是一种超快的方式:

>> counts = sparse(x(1:end-1),x(2:end),1)
counts =
   (5,1)        1
   (1,2)        2
   (2,3)        1
   (3,4)        1
   (4,5)        1
Run Code Online (Sandbox Code Playgroud)

您可以简单地转换为完整矩阵: full(counts)


这是一个等效的解决方案accumarray:

>> counts = accumarray([x(1:end-1);x(2:end)]', 1)
counts =
     0     2     0     0     0
     0     0     1     0     0
     0     0     0     1     0
     0     0     0     0     1
     1     0     0     0     0
Run Code Online (Sandbox Code Playgroud)

  • Nerdgasm,有人吗?(1) (4认同)