Matrix Multiplication with NumPy
Python Pandas Numpy: Exercise-25 with Solution
Perform matrix multiplication using NumPy.
Sample Solution:
Python Code:
import numpy as np
# Create two matrices
matrix1 = np.array([[1, 2, 3],
[4, 5, 6]])
matrix2 = np.array([[7, 8],
[9, -10],
[11, 12]])
# Perform matrix multiplication using numpy.dot()
result_matrix = np.dot(matrix1, matrix2)
# Alternatively, you can use the @ operator
# result_matrix = matrix1 @ matrix2
# Display the result
print(result_matrix)
Output:
[[ 58 24] [139 54]]
Explanation:
Here's a breakdown of the above code:
- We create two matrices, "matrix1" and "matrix2", where the number of columns in "matrix1" matches the number of rows in "matrix2".
- The np.dot(matrix1, matrix2) function (or the matrix1 @ matrix2 operation) performs matrix multiplication.
- The resulting "result_matrix" is the product of the two matrices.
- The result is printed, showing the matrix multiplication result.
Flowchart:
Python Code Editor:
Previous: Concatenating NumPy Arrays Vertically.
Next: Cumulative sum of a NumPy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/pandas_numpy/pandas_numpy-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics