14wml
14wml

Reputation: 4166

Is there a way to multiply/divide a matrix by a corresponding cell in numpy?

Basically I have this matrix A:

[[1, 2, 3],
 [2, 4, 6],
 [3, 6, 9],
 [4, 8, 12]]

And I have this other matrix B (in which each column is the sum of the corresponding column in A):

[[10, 20, 30],
 [10, 20, 30],
 [10, 20, 30],
 [10, 20, 30]]

And I would like my resulting matrix C to be like this:

[[1/10, 2/20, 3/30],
 [2/10, 4/20, 6/30],
 [3/10, 6/20, 9/30],
 [4/10, 8/20, 12/30]]

Is there a way to do this in numpy or do I have to use for loops? I'd really prefer not to use for loops b/c they are slow so if anyone has an answer for this I'd really appreciate it!

Upvotes: 1

Views: 286

Answers (1)

Matt Hall
Matt Hall

Reputation: 8142

If the arrays are the same shape, you can just do the division directly:

import numpy as np
a = np.array([[1, 2, 3],
              [2, 4, 6],
              [3, 6, 9],
              [4, 8, 12]])

b = np.array([[10, 20, 30],
              [10, 20, 30],
              [10, 20, 30],
              [10, 20, 30]])

a / b

Gives the following in Python 3 (you'll get integer division in Python 2, unless you do, say, a.astype(float) / b):

array([[ 0.1,  0.1,  0.1],
       [ 0.2,  0.2,  0.2],
       [ 0.3,  0.3,  0.3],
       [ 0.4,  0.4,  0.4]])

Since there's a lot of redundancy in b, you can even do:

a / [10, 20, 30]

where the [10, 20, 30] could equally well come from np.sum(a, axis=0). Either way, NumPy's broadcasting will take care of matching the shape of the arrays to get a sensible answer.

Upvotes: 2

Related Questions