Python Program to Add Two Matrices
A matrix is a rectangular array of numbers, symbols, or expressions arranged in rows and columns. Matrices are often used in mathematics, engineering, physics, computer science, and other fields to represent and manipulate data.
Each element in a matrix is identified by its row and column position, which is referred to as its indices.
Python Code :
The below Python program adds two matrices:
# Define matrices A and B A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]] # Create a matrix to hold the result C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Add matrices A and B element-wise and store the result in C for i in range(len(A)): for j in range(len(A)): C[i][j] = A[i][j] + B[i][j] # Display the resulting matrix C for row in C: print(row)
The matrices A and B are defined as 3x3 lists of lists.
A matrix C is created as a 3x3 list of lists initialized to all zeros.
The matrices A and B are added element-wise using a nested for loop that iterates over the rows and columns of the matrices. The result of each addition is stored in the corresponding position of the matrix C.
The resulting matrix C is displayed using a for loop that iterates over the rows of the matrix and prints each row.
[10, 10, 10] [10, 10, 10] [10, 10, 10]