I have a large matrix of N = 10000 3d vectors. To simplify, I will use a 10 x 3 matrix here as an example:
import numpy as np
A = np.array([[1.2, 2.3, 0.8],
[3.2, 2.1, 0.5],
[0.8, 4.4, 4.4],
[-0.2, -1.1, -1.1],
[2.4, 4.6, 1.6],
[0.5, 0.96, 0.33],
[1.1, 2.2, 3.3],
[-2.2, -4.41, -6.62],
[3.4, 5.5, 3.8],
[-5.1, -28., -28.1]])
I want to find all unique pairs of vectors that are nearly parallel to each other. A tolerance measurement needs to be used, and I want to get the all unique pairs of row indexes (regardless of the order). I managed to write the following code:
def all_parallel_pairs(A, tol=0.1):
res = set()
for i, v1 in enumerate(A):
for j, v2 in enumerate(A):
if i == j:
continue
norm = np.linalg.norm(np.cross(v1, v2))
if np.isclose(norm, 0., rtol=0, atol=tol):
res.add(tuple(sorted([i, j])))
return np.array(list(res))
print(all_parallel_pairs(A, tol=0.1))
out[1]: [[0 4]
[2 3]
[6 7]
[4 5]
[0 5]]
However, since I am using two for loops, it becomes slow when N is large. I feel like there should be more efficient and Numpyic ways to do this. Any suggestions?