Certainly! Below is a Python function that implements matrix multiplication in a way that emphasizes readability and Pythonic style. It includes input validation to ensure that matrices can be legally multiplied (i.e., the number of columns in the first matrix must equal the number of rows in the second matrix).
python
def matrix_multiply(A, B):
"""
Multiplies two matrices A and B.
Parameters:
A (list of list of int/float): The first matrix.
B (list of list of int/float): The second matrix.
Returns:
list of list of int/float: The product of the two matrices.
Raises:
ValueError: If the matrices cannot be multiplied due to incompatible dimensions.
"""
# Validate input matrices dimensions
num_rows_A, num_cols_A = len(A), len(A[0])
num_rows_B, num_cols_B = len(B), len(B[0])
if num_cols_A != num_rows_B:
raise ValueError("The number of columns in the first matrix must be equal to the number of rows in the second matrix.")
# Initialize result matrix with zeros
result = [[0 for _ in range(num_cols_B)] for _ in range(num_rows_A)]
# Perform matrix multiplication
for i in range(num_rows_A):
for j in range(num_cols_B):
for k in range(num_cols_A):
result[i][j] += A[i][k] * B[k][j]
return result
# Example usage:
A = [
[1, 2, 3],
[4, 5, 6]
]
B = [
[7, 8],
[9, 10],
[11, 12]
]
try:
C = matrix_multiply(A, B)
for row in C:
print(row)
except ValueError as e:
print(e)
This function defines matrix_multiply which takes two matrices A and B and returns their product. It first checks that the number of columns in A is equal to the number of rows in B. It then initializes a result matrix with the appropriate dimensions and zeroes. Finally, it computes the product using nested loops.
The example usage demonstrates how to call the function and print the resulting matrix. If the matrices provided cannot be multiplied due to dimension mismatch, the function will raise a ValueError with an appropriate message.