Calculate Difference Between All Combinations Of Entries In A Vector
I have a numpy 1D array of z values, and I want to calculate the difference between all combinations of the entries, with the output as a square matrix. I know how to calculate th
Solution 1:
Simple one line solution using numpy array broadcasting.
import numpy as np
z = np.array([1, 5, 8])
# Simple one line solution
z - z.reshape(-1,1)
Output:
array([[ 0, 4, 7],
[-4, 0, 3],
[-7, -3, 0]])
Solution 2:
In [29]: z = np.array([1, 5, 8])
In [30]: -np.subtract.outer(z, z)
Out[30]:
array([[ 0, 4, 7],
[-4, 0, 3],
[-7, -3, 0]])
(Drop the minus sign if you don't care about the sign convention.)
Solution 3:
I've worked out I can get the answer I want with a double iterator, although I'm not sure it is the most efficient for very large arrays
np.array([j-i for i in z for j in z]).reshape(len(z),len(z))
output:
array([[ 0, 4, 7],
[-4, 0, 3],
[-7, -3, 0]])
EDIT: so indeed the other two solutions are about 50 times faster:
python3 -m timeit -s "import numpy as np" -s "z=np.random.uniform(size=5000)""z-z.reshape(-1,1)"2 loops, best of 5: 119 msec per loop
python3 -m timeit -s "import numpy as np" -s "z=np.random.uniform(size=5000)""np.subtract.outer(z, z)"2 loops, best of 5: 118 msec per loop
python3 -m timeit -s "import numpy as np" -s "z=np.random.uniform(size=5000)""np.array([j-i for i in z for j in z]).reshape(len(z),len(z))"1loop, best of 5: 5.18 sec per loop
Post a Comment for "Calculate Difference Between All Combinations Of Entries In A Vector"