# Define two matrices A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]] # Create an empty matrix to store the result C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Calculate the sum of the matrices for i in range(len(A)): for j in range(len(A[0])): C[i][j] = A[i][j] + B[i][j] # Print the result for row in C: print(row)
[10, 10, 10] [10, 10, 10] [10, 10, 10]
import numpy as np # Define two matrices as NumPy arrays A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) # Calculate the sum of the matrices C = A + B # Print the result print(C)
[[10 10 10] [10 10 10] [10 10 10]]In the first example, the matrix addition is performed using nested loops. The result is stored in an empty matrix C that has the same dimensions as the input matrices. In the second example, the matrix addition is performed using NumPy, a popular scientific computing package for Python. NumPy provides a fast and efficient way to perform matrix operations, including matrix addition. To perform matrix addition using NumPy, we simply need to create NumPy arrays for the input matrices and add them using the "+" operator. The result is another NumPy array that contains the sum of the input matrices.