Reputation:
What I want is really simple but I can't figure out how to do it on numpy.
I have the following matrix:
M = [[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
And this array:
A = [1, 2, 3]
I want to multiply the matrix with each element on the array on a way to produce:
[[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[3, 3, 3],
[3, 3, 3],
[3, 3, 3]]]
without any for loops, I want just a numpy function.
Upvotes: 0
Views: 98
Reputation: 231355
In [146]: M = np.ones((3,3),int)
In [147]: M
Out[147]:
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
In [148]: A = np.array([1,2,3])
broadcasted multiplication does this:
In [149]: A[:,None,None]*M
Out[149]:
array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[3, 3, 3],
[3, 3, 3],
[3, 3, 3]]])
A
is changed to (3,1,1); M
is automatically broadcast to (1,3,3), together (3,3,3)
Upvotes: 3
Reputation: 51165
Using einsum
np.einsum('ij,k->kji', M, A)
array([[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[3, 3, 3],
[3, 3, 3],
[3, 3, 3]]])
Upvotes: 3