In this python numpy program, we willl add a vector to each row of a matrix using NumPy.
Steps to solve the program
- Import the numpy library as np.
- Create a matrix and a vector using np.array().
- Use for loop to iterate over the rows of the matrix.
- During iteration add the vector to the row using indexing and some logic.
- Print the output.
import numpy as np
x = np.array([[5, 3],
[7, 4]])
print("Original matrix: \n",x)
vector = np.array([2,5])
print("Vector to be added: \n",vector)
for i in range(len(x)):
x[i,:] = x[i,:]+vector
print("Matrix after adding a vector: \n",x)
Output :
Original matrix:
[[5 3]
[7 4]]
Vector to be added:
[2 5]
Matrix after adding a vector:
[[7 8]
[9 9]]