I want to list all possible pairs of the integers [1, n]
with a large n
. I find myself looking for the fastest option. This is what I've come up with so far.
Matlab's nchoosek
and combnk
methods recommend n<15
for listing all possible combinations because of the explosive number of combinations. So how fast this is depends on the n.
pair = nchoosek(1:n, 2);
Another option would be to use a nested for loop
kk =1;
pair = zeros(nchoosek(n, 2), 2);
for ii = 1:n
for jj = ii+1:n
pair(kk, :) = [ii, jj];
kk = kk + 1;
end
end
This would be relatively slow.
I also thought of using the ind2sub
function directly
pair_adjacency = tril(ones(n), -1);
[x, y] = ind2sub(size(pair_adjacency), find(pair_adjacency==1));
pair = [x, y];
Timing these methods in a loop, 10 times each with n=1000
, I get fastest to slowest
- ind2sub (0.15 sec)
- for loop (16.3 sec)
- nchoosek (16.8 sec)
It seems like ind2sub
is the fastest way to go by a long shot. Just out of curiosity, what are other options that may or may not be faster?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…