Niro
Niro

Reputation: 443

Column wise scalar multiplication of matrix x vector

Basically, I want to perform column wise scalar multiplication of a matrix A and vector B. Where every column of matrix A is multiplied by the corresponding value in vector B. I have a method that looks like this.

def scale_matrix(self, matrix, vector):
    """
    Performs scalar multiplication of matrix and vector column wise
    """
    for value, index in enumerate(vector):
        matrix[:, index] *= value
    return matrix

I am using numpy somewhere else in my code, I was wondering if this can be achieved using only numpy?

Upvotes: 0

Views: 1543

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53029

If your matrix is an MxN numpy array and your vector an N vector then you can simply do

matrix * vector

or

matrix *= vector

if you want it in-place.

Note that this won't work if either matrix or vector is of the np.matrix class. It has to be np.ndarray.

Explanation: By the numpy broadcasting rules if the operands have shapes of different lengths then the shorter one is filled with ones on the left. This leads to shapes (M, N) and (1, N). 1-axes are broadcast, i.e. along this axis values are repeated on the fly to match the shape of the other operand

Upvotes: 1

Related Questions