Divide the vector column of a matrix

Viewed 153

Suppose the matrix

X = np.array([[ 1,  2,  3],
              [ 4,  5,  6],
              [ 7,  8,  9],
              [10, 11, 12]])

and the vector divisor = [5, 10, 15]. Is there a method using numpy to divide the first column of X by divisor[0], the second column of X by divisor[1] and the second column of X by divisor[3]?

1 Answers

Simply divide them and let numpy take care of broadcasting:

X/divisor

output:

[[0.2 0.2 0.2]
 [0.8 0.5 0.4]
 [1.4 0.8 0.6]
 [2.  1.1 0.8]]

And if you want to divide the rows (instead of columns) use:

X/divisor[:,None]

Which adds a dimension to divisor so numpy can correctly broadcast it.

Related