Search code examples
pythonnumpymatrixipythonmultiplication

multiplying one row in a matrix with a scalar value but keeping the whole matrix


I was wondering how I can multiply a scalar value to a specific row in a matrix of ones?

I know there is a similar question here: similar

But it's different in the sense that by simply doing the multiplication, I lose the rest of the matrix. The output would only be a row from that matrix. I want the whole matrix with only that row changed.


Solution

  • As @Lior T commented, the best way to do this in NumPy is by reassigning the row with a new array. The following code multiplies row 2 by 5.2, leaving the rest of the matrix unchanged.

    >>> import numpy as np
    >>> a = np.ones((5, 5))
    >>> a
    array([[1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.]])
    >>> a[2] = a[2] * 5.2
    >>> a
    array([[1. , 1. , 1. , 1. , 1. ],
           [1. , 1. , 1. , 1. , 1. ],
           [5.2, 5.2, 5.2, 5.2, 5.2],
           [1. , 1. , 1. , 1. , 1. ],
           [1. , 1. , 1. , 1. , 1. ]])