Python Write a Program to Implement Matrix Multiplication

Document 对象参考手册Python3 Examples

Matrix multiplication is a basic operation in linear algebra. Given two matrices A and B, the result of matrix multiplication is a new matrix C, where each element of C is the dot product of the corresponding row of A and the corresponding column of B. Assuming A is an m×n matrix and B is an n×p matrix, the resulting matrix C will be an m×p matrix.

Example

def matrix_multiply(A, B):
    # Get the dimensions of matrices A and B
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    # Check if the number of columns of matrix A equals the number of rows of matrix B
    if cols_A != rows_B:
        raise ValueError("The number of columns of matrix A must equal the number of rows of matrix B")

    # Initialize the result matrix C with size rows_A x cols_B
    C = [[0 for _ in range(cols_B)] for _ in range(rows_A)]

    # Perform matrix multiplication
    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

# Example matrices
A = [[1, 2, 3],
     [4, 5, 6]]

B = [[7, 8],
     [9, 10],
     [11, 12]]

# Call the matrix multiplication function
result = matrix_multiply(A, B)

# Output the result
for row in result:
    print(row)

Code explanation:

  1. matrix_multiplyThe function takes two matrices A and B as input.
  2. First, get the dimensions of matrices A and B, and check whether the number of columns of matrix A equals the number of rows of matrix B. If they are not equal, raise an error.
  3. Initialize the result matrix C with sizerows_A x cols_B, with all elements initialized to 0.
  4. Use a triple loop to perform the matrix multiplication calculation. The outer loop iterates over the rows of A, the middle loop iterates over the columns of B, and the inner loop calculates the dot product and accumulates it into the corresponding position of C.
  5. Finally, return the result matrix C.

Output result:

[58, 64]
[139, 154]

Document 对象参考手册Python3 Examples

Other extensions