In this article, we will implement a Python function to multiply two matrices. Matrix multiplication is a fundamental operation in various fields such as mathematics, physics, and computer science. The resultant matrix is obtained by taking the dot product of rows and columns from the two input matrices.
import numpy as np
def matrix_multiply(A, B):
return np.dot(A, B)
# Example usage
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = matrix_multiply(A, B)
print(result)
The implementation the above code is as follows –
- Importing NumPy: The line
import numpy as np
imports the NumPy library and allows us to use it with the aliasnp
. - Defining the Function: The function
matrix_multiply(A, B)
takes two matrices as input. Inside the function,np.dot(A, B)
computes the dot product of matrices A and B, returning the resulting matrix. - Calling the Function: The function is called with the matrices A and B, and the result is stored in the variable
result
.