I know I can do np.subtract.outer(x, x)
. If x
has shape (n,)
, then I end up with an array with shape (n, n)
. However, I have an x
with shape (n, 3)
. I want to output something with shape (n, n, 3)
. How do I do this? Maybe np.einsum
?
Asked
Active
Viewed 1,869 times
6

Neil G
- 32,138
- 39
- 156
- 257
1 Answers
11
You can use broadcasting
after extending the dimensions with None
/np.newaxis
to form a 3D array version of x
and subtracting the original 2D array version from it, like so -
x[:, np.newaxis, :] - x
Sample run -
In [6]: x
Out[6]:
array([[6, 5, 3],
[4, 3, 5],
[0, 6, 7],
[8, 4, 1]])
In [7]: x[:,None,:] - x
Out[7]:
array([[[ 0, 0, 0],
[ 2, 2, -2],
[ 6, -1, -4],
[-2, 1, 2]],
[[-2, -2, 2],
[ 0, 0, 0],
[ 4, -3, -2],
[-4, -1, 4]],
[[-6, 1, 4],
[-4, 3, 2],
[ 0, 0, 0],
[-8, 2, 6]],
[[ 2, -1, -2],
[ 4, 1, -4],
[ 8, -2, -6],
[ 0, 0, 0]]])

Divakar
- 218,885
- 19
- 262
- 358
-
1Well, this was a lot simpler than I anticipated :) – Neil G Sep 09 '15 at 07:50