Suppose the following numpy array:
JavaScript
x
2
1
arr = np.array([0, 1, 2, 3, 4]) # can be any array
2
I want to know the fastest way to generate the following operation:
JavaScript
1
10
10
1
n = arr.shape[0]
2
result = np.tile(arr, (n, 1)) - arr.reshape((-1, 1))
3
print(result):
4
5
array([[ 0, 1, 2, 3, 4],
6
[-1, 0, 1, 2, 3],
7
[-2, -1, 0, 1, 2],
8
[-3, -2, -1, 0, 1],
9
[-4, -3, -2, -1, 0]])
10
(1) How to efficiently create matrix “result” (because n >> 0 can be very large) ?
(2) Does this matrix have a particular name ?
Advertisement
Answer
This is a bit faster:
JavaScript
1
2
1
result = arr-arr[:,None]
2
cursory benchmarks, nothing scientific. (timeit 100 times with arr):
JavaScript
1
5
1
5 items (arr) 100 times 10,000 items (np.arange) once
2
OP: 0.0006383560000000066 0.7902513520000001
3
This one: 0.0001735200000000381 0.3640661519999999
4
Kelly's: 0.00027326299999996806 0.36036748900000015 (see comments)
5