Search code examples
pythonvectorization

Vectorising a sum of scalar multiplied by a matrix, where the scaler is an element of a list


I'm trying to vectorise the following

a = np.array([1,2])
b = np.array([[5,5],[5,5]])
target = 0
for _ in a:
    target = target + _ * b
    

The above yields a 2x2 matrix where all entries are 15. How can I achieve this through vectorisation? I've been trying to cast a to be two 2x2 matrices, but I'm not getting anywhere

Thanks


Solution

  • This looks like a simple:

    b * a.sum()
    

    Output:

    array([[15, 15],
           [15, 15]])