Reputation: 3862
I have 2 arrays. "A" is one of them with arbitrary length (let's assume 1000 entries for a start), where each point holds a n-dimensional vector, where each entry represents a scalar. "B" is the other one, with n entries that each hold a 3-dimensional vector. How can I do a scalar multiplication, so that the result is one array "C", where each entry is the scalar multiplication of each of the n scalars with each of the n 3-Dimensional Vectors?
As an example in 4-D:
a=[[1,2,3,4],[5,6,7,8],....]
b=[[1,0,0],[0,1,0],[0,0,1],[1,1,1]]
and a result
c=[[1*[1,0,0],2*[0,1,0],3*[0,0,1],4*[1,1,1]] , [5*[1,0,0],...],...]
The implementation should be in numpy without to large for loops, because there are expected to be way more than 1000 entries. n is expected to be 7 in our case.
Upvotes: 3
Views: 148
Reputation: 9172
If you start with:
a = np.array([[1,2,3,4],[5,6,7,8]])
b = np.array([[1,0,0],[0,1,0],[0,0,1],[1,1,1]])
Then we can add an extra axis to a
, and repeating the array along it gives us...
>>> a[:,:,None].repeat(3, axis=2)
array([[[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]],
[[5, 5, 5],
[6, 6, 6],
[7, 7, 7],
[8, 8, 8]]])
Now, as @Jaime says, there is no need to use the repeat
while operating, because NumPy's broadcasting takes care of it:
>>> a[:,:,None] * b
array([[[1, 0, 0],
[0, 2, 0],
[0, 0, 3],
[4, 4, 4]],
[[5, 0, 0],
[0, 6, 0],
[0, 0, 7],
[8, 8, 8]]])
Upvotes: 3