How about using some linear algebra? The distance of two points can be computed from the inner product of their position vectors,
D(x, y) = ∥y – x∥ = √ (
xT x + yT y – 2 xT y ),
and the inner product for all pairs of points can be obtained through a simple matrix operation.
x = [xl(:)'; yl(:)'; zl(:)'];
IP = x' * x;
d = sqrt(bsxfun(@plus, diag(IP), diag(IP)') - 2 * IP);
For 10000 points, I get the following timing results:
- ahmad's loop + shoelzer's preallocation: 7.8 seconds
- Dan's vectorized indices: 5.3 seconds
- Mohsen's bsxfun: 1.5 seconds
- my solution: 1.3 seconds
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…