给定一个整数向量,例如:
X = [1 2 3 4 5 1 2]
我想找到一种非常快速的方法来计算具有 2 个元素的唯一组合的数量。
在这种情况下,两个数字的组合是:
[1 2] (occurs twice)
[2 3] (occurs once)
[3 4] (occurs once)
[4 5] (occurs once)
[5 1] (occurs once)
就目前而言,我目前在 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
有没有更快/更智能的方式来做到这一点?