# numpy.outer without flatten

$$x$$ is an $$N \times M$$ matrix.

$$y$$ is a $$1 \times L$$ vector.

I want to return "outer product" between $$x$$ and $$y$$, let's call it $$z$$.

z[n,m,l] = x[n,m] * y[l]


I could probably do this using einsum.

np.einsum("ij,k->ijk", x[:, :, k], y[:, k])


or reshape afterwards.

 np.outer(x[:, :, k], y).reshape((x.shape[0],x.shape[1],y.shape[0]))


But I'm thinking of doing this in np.outer only or something seems simpler, memory efficient.

Is there a way?

I think numpy.tensordot does what you need.

import numpy as np

N=2
M=3
L=4

x=np.arange(N*M).reshape(N,M)
y=np.arange(L)
z=np.tensordot(x,y,axes=0)

print('x=',x)
print('y=',y)
print('z=',z)


x= [[0 1 2]
[3 4 5]]
y= [0 1 2 3]
z= [[[ 0  0  0  0]
[ 0  1  2  3]
[ 0  2  4  6]]

[[ 0  3  6  9]
[ 0  4  8 12]
[ 0  5 10 15]]]