Python program that uses nested loops to multiply two matrices:

Created with Sketch.

Python program that uses nested loops to multiply two matrices:

def multiply_matrices(A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

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

    if cols_A == rows_B:
        for i in range(rows_A):
            for j in range(cols_B):
                for k in range(cols_A):
                    C[i][j] += A[i][k] * B[k][j]
        return C
    else:
        return "The number of columns of the first matrix must be equal to the number of rows of the second matrix"

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

The function multiply_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 with rows of the first matrix and columns of the second matrix and all elements initialized to 0, using list comprehension. The nested for loop runs for the number of rows and columns and performs the multiplication of the corresponding elements 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 multiplication of two matrices A and B.

The example usage creates two matrices A and B and calls the multiply_matrices() function to multiply them together, and then prints the resulting matrix. This program assumes that the number of columns of first matrix is equal to the number of rows of the second matrix. If not it will raise an error or return an error message.

It’s also important to note that matrix multiplication is not commutative, meaning the order of the matrices being multiplied matters.

Leave a Reply

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