Add a vector to each row of a matrix using NumPy.

In this python numpy program, we willl add a vector to each row of a matrix using NumPy.

Steps to solve the program
  1. Import the numpy library as np.
  2. Create a matrix and a vector using np.array().
  3. Use for loop to iterate over the rows of the matrix.
  4. During iteration add the vector to the row using indexing and some logic.
  5. 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]]
				
			

calculate the inner/dot product of two vectors.

convert the list into an array.

Leave a Comment