w3resource

Matrix Multiplication in Python Using list comprehensions

Write a Python function that performs matrix multiplication using list comprehensions.

The task is to create a Python function that performs matrix multiplication using list comprehension. This function will take two matrices as input and compute their product by implementing the mathematical rules of matrix multiplication. Using list comprehension, the function will efficiently iterate over the rows and columns of the input matrices to produce the resulting matrix. This approach ensures concise and readable code while maintaining computational efficiency.

Sample Solution:

Python Code :

# Define a function to perform matrix multiplication of matrices A and B
def matrix_multiplication(A, B):
    """
    Perform matrix multiplication of matrices A and B.

    Args:
    A: First matrix (list of lists).
    B: Second matrix (list of lists).

    Returns:
    Result of matrix multiplication (list of lists).
    """
    if len(A[0]) != len(B):
        raise ValueError("Number of columns in A must equal number of rows in B")

    # Number of rows and columns in resulting matrix
    num_rows_A = len(A)
    num_cols_B = len(B[0])

    # Perform matrix multiplication using list comprehension
    result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(num_cols_B)] for i in range(num_rows_A)]

    return result

# Example usage:
if __name__ == "__main__":
    # Example matrices A and B
    A = [[1, 2, 3],
         [4, 5, 6]]

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

    # Print the result of matrix multiplication
    print(matrix_multiplication(A, B))

Output:

[[58, 64], [139, 154]]

Explanation:

  • The above code defines a function "matrix_multiplication()" that performs matrix multiplication of two matrices 'A' and 'B'. Here's a breakdown:
  • The function takes two matrices 'A' and 'B' as input arguments.
  • It checks whether the number of columns in matrix 'A' is equal to the number of rows in matrix 'B'. If not, it raises a "ValueError".
  • It calculates the number of rows in matrix 'A' and the number of columns in matrix 'B', which are needed to determine the size of the resulting matrix.
  • The matrix multiplication is performed using a nested list comprehension. For each element in the resulting matrix, it calculates the sum of the products of the corresponding elements from rows of matrix 'A' and columns of matrix 'B'.
  • The resulting matrix is returned.
  • An example usage section demonstrates how to use the "matrix_multiplication()" function with sample matrices 'A' and 'B', printing the result of their multiplication.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Develop a Custom Iterator for Tree data structures in Python.
Next: Python Metaclass Tutorial: Validate Attributes as Integers

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.