Divide Matrix by Vector in Numpy
 Divide Matrix by Vector in Numpy With the Array Slicing Method in Python
 Divide Matrix by Vector in Numpy With the Transpose Method in Numpy

Divide Matrix by Vector in Numpy With the
numpy.reshape()
Function
This tutorial will discuss the methods to divide a matrix by a vector in Numpy.
Divide Matrix by Vector in Numpy With the Array Slicing Method in Python
A matrix is a 2D array, while a vector is just a 1D array. If we want to divide the elements of a matrix by the vector elements in each row, we have to add a new dimension to the vector. We can add a new dimension to the vector with the array slicing method in Python. The following code example shows us how to divide each row of a matrix by a vector with the array slicing method in Python.
import numpy as np
matrix = np.array([[2,2,2],[4,4,4],[6,6,6]])
vector = np.array([2,4,6])
matrix = matrix / vector[:,None]
print(matrix)
Output:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
We first created the matrix and the vector with the np.array()
function. We then added a new axis to the vector with the slicing method. We then divided the matrix by the array and saved the result inside the matrix.
Divide Matrix by Vector in Numpy With the Transpose Method in Numpy
We can also transpose the matrix to divide each row of the matrix by each vector element. After that, we can transpose the result to return to the matrix’s previous orientation. See the following code example.
import numpy as np
matrix = np.array([[2,2,2],[4,4,4],[6,6,6]])
vector = np.array([2,4,6])
matrix = (matrix.T / vector).T
print(matrix)
Output:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
In the above code, we took a transpose of the matrix and divided it by the vector. After that, we took a transpose of the result and stored it inside the matrix
.
Divide Matrix by Vector in Numpy With the numpy.reshape()
Function
The whole idea behind this approach is that we have to convert the vector to a 2D array first. The numpy.reshape()
function can be used to convert the vector into a 2D array where each row contains only one element. We can then easily divide each row of the matrix by each row of the vector.
import numpy as np
matrix = np.array([[2,2,2],[4,4,4],[6,6,6]])
vector = np.array([2,4,6])
matrix = matrix / vector.reshape((3,1))
print(matrix)
Output:
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
In the above code, we converted the vector
to a 2D array with the np.reshape()
function. After that, we divided the matrix
by the vector
and stored the result inside the matrix
.