Search code examples
pythonnumpymatrixvectorizationmatrix-multiplication

element wise multiplication of a vector and a matrix with numpy


Given python code with numpy:

import numpy as np
a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.shape = (3, 2)
b = np.arange(3) + 1             # b = [1, 2, 3]               ; b.shape = (3,)

How can I multiply each value in b with each corresponding row ('vector') in a? So here, I want the result as:

result = [[0, 1], [4, 6], [12, 15]]    # result.shape = (3, 2)

I can do this with a loop, but I am wondering about a vectorized approach. I found an Octave solution here. Apart from this, I didn't find anything else. Any pointers for this? Thank you in advance.


Solution

  • Probably the simplest is to do the following.

    import numpy as np
    a = np.arange(6).reshape(3, 2)   # a = [[0, 1], [2, 3], [4, 5]]; a.shape = (3, 2)
    b = np.arange(3) + 1  
    
    ans = np.diag(b)@a
    

    Here's a method that exploits numpy multiplication broadcasting:

    ans = (b*a.T).T
    

    These two solutions basically take the same approach

    ans = np.tile(b,(2,1)).T*a
    ans = np.vstack([b for _ in range(a.shape[1])]).T*a