Special vector and elemental multiplication

I have 2 arrays. "A" is one of them with an arbitrary length (let's say 1000 entries to start with), where each point contains an n- dimensional vector, where each entry is a scalar. "B" is another, with elements n , each of which has a three-dimensional vector. How can I do scalar multiplication, so that the result is a single "C" array, where each record is a scalar multiplication of each of n scalars with each of 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 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 large loops, as it is expected that there will be more than 1000 entries. n is expected in our case 7.

+3
source share
1 answer

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 additional 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 it repeatwhile you work, because NumPy broadcast will take care of this:

>>> 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]]])
+3
source

All Articles