Python Program to add two matrices

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

  1. Start
  2. Define the matrices: Initialize two matrices of the same size.
  3. Check matrix dimensions: Ensure that both matrices have the same dimensions.
  4. Initialize a result matrix: Create a matrix with the same dimensions to store the result.
  5. Loop through the rows and columns: Use nested loops to iterate through each element of the matrices and perform the addition.
  6. Store the result: Add the corresponding elements of the two matrices and store the result in the new matrix.
  7. Display the result: Print the resultant matrix after addition.
  8. 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

  1. Defining the matrices:
    The matrices matrix_a and matrix_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.
  2. Initializing the result matrix:
    A result matrix result is initialized with all zeroes. This matrix will store the sum of the corresponding elements from matrix_a and matrix_b.
  3. 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 of matrix_a and matrix_b, and stores the result in result[i][j].
  4. Displaying the output:
    The program uses a for loop to print each row of the result matrix after the addition is completed.

Python

4854

895

Related Articles