Python program that uses nested loops to add two matrices of the same size

Created with Sketch.

Python program that uses nested loops to add two matrices of the same size

def add_matrices(A, B):
    rows = len(A)
    cols = len(A[0])

    # Initialize result matrix with zeros
    C = [[0 for j in range(cols)] for i in range(rows)]

    for i in range(rows):
        for j in range(cols):
            C[i][j] = A[i][j] + B[i][j]
    return C

# Example usage
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
print(add_matrices(A, B))

The function add_matrices(A, B) takes two 2D matrices A and B as arguments. It first determines the number of rows and columns of the matrices using the len() function. Then it creates a new 2D matrix C of the same size, with all elements initialized to 0, using list comprehension. The nested for loop runs for the number of rows and columns and performs the addition of the corresponding element of matrix A and B and assigns it to the corresponding element of matrix C. Finally, it returns the matrix C which is the resultant matrix of the addition of two matrices A and B.

The example usage creates two matrices A and B and calls the add_matrices() function to add them together, and then prints the resulting matrix. This program assumes that the matrices are of the same size, if not it will raise an error.

Leave a Reply

Your email address will not be published. Required fields are marked *