Write a Python program to add two matrices. A matrix is a 2D array of numbers, and matrix addition is performed by adding the corresponding elements of two matrices.
Input-Output Examples
plaintext
Example 1:
Input:
Matrix A:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Matrix B:
[[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
Output:
The resultant matrix after addition is:
[[10, 10, 10],
[10, 10, 10],
[10, 10, 10]]
Example 2:
Input:
Matrix A:
[[1, 0],
[0, 1]]
Matrix B:
[[1, 2],
[3, 4]]
Output:
The resultant matrix after addition is:
[[2, 2],
[3, 5]]
Algorithm to add two matrices
- Start
- Define the matrices: Initialize two matrices of the same size.
- Check matrix dimensions: Ensure that both matrices have the same dimensions.
- Initialize a result matrix: Create a matrix with the same dimensions to store the result.
- Loop through the rows and columns: Use nested loops to iterate through each element of the matrices and perform the addition.
- Store the result: Add the corresponding elements of the two matrices and store the result in the new matrix.
- Display the result: Print the resultant matrix after addition.
- End
Python Program to add two matrices
python
# Python program to add two matrices
# Define two 3x3 matrices
matrix_a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix_b = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
# Initialize an empty matrix to store the result (same dimensions as matrix_a and matrix_b)
result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# Loop through the rows and columns to perform matrix addition
for i in range(len(matrix_a)): # Loop through rows
for j in range(len(matrix_a[0])): # Loop through columns
result[i][j] = matrix_a[i][j] + matrix_b[i][j]
# Display the result matrix
print("The resultant matrix after addition is:")
for row in result:
print(row)
Code Explanation
- Defining the matrices:
The matricesmatrix_a
andmatrix_b
are predefined as two-dimensional lists in Python. Each matrix has the same dimensions (3x3 in this case) so that matrix addition can be performed. - Initializing the result matrix:
A result matrixresult
is initialized with all zeroes. This matrix will store the sum of the corresponding elements frommatrix_a
andmatrix_b
. - Looping through the matrices:
The program uses two nested loops:- The outer loop iterates over the rows of the matrices.
- The inner loop iterates over the columns of the matrices. For each element at position
(i, j)
, the program adds the corresponding elements ofmatrix_a
andmatrix_b
, and stores the result inresult[i][j]
.
- Displaying the output:
The program uses afor
loop to print each row of the result matrix after the addition is completed.