Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special Vector and Element-wise Multiplication

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.

like image 826
Dschoni Avatar asked Feb 10 '26 22:02

Dschoni


1 Answers

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]]])
like image 89
Ricardo Cárdenes Avatar answered Feb 13 '26 16:02

Ricardo Cárdenes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!