From 40f55dbf7d80bfc98981aa4ae7a63f1f35b0a09a Mon Sep 17 00:00:00 2001 From: Donald Calloway Date: Thu, 2 Oct 2025 08:44:32 -0700 Subject: [PATCH] Adding function to multiply matrices --- matrix_mult.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 matrix_mult.py diff --git a/matrix_mult.py b/matrix_mult.py new file mode 100644 index 0000000..e487ac1 --- /dev/null +++ b/matrix_mult.py @@ -0,0 +1,53 @@ + + +from typing import List +""" +Multiplies two matrices M and N and returns the resulting matrix. +Args: + M (List[List]): The first matrix as a list of lists, with dimensions m x k. + N (List[List]): The second matrix as a list of lists, with dimensions k x n. +Returns: + List[List]: The product matrix as a list of lists, with dimensions m x n. +Raises: + AssertionError: If the number of columns in M does not equal the number of rows in N. +Example: + >>> M = [ + ... [1, 2, 4], + ... [0, 1, 2] + ... ] + >>> N = [ + ... [1, 2], + ... [3, 4], + ... [0, 1] + ... ] + >>> multiply(M, N) + [[7, 14], [3, 6]] +""" + + +def multiply(M: List[List], N: List[List]) -> List[List]: + mrows, mcols = len(M), len(M[0]) + nrows, ncols = len(N), len(N[0]) + assert mcols == nrows, "Matrices are not compatible for multiplication" + # Initialize result matrix with zeros + result = [[0 for _ in range(ncols)] for _ in range(mrows)] + for i in range(mrows): + for j in range(ncols): + for k in range(mcols): + result[i][j] += M[i][k] * N[k][j] + return result + + + +M = [ + [1, 2, 4], + [0, 1, 2] +] + +N = [ + [1, 2], + [3, 4], + [0, 1] +] + +print(multiply(M, N)) \ No newline at end of file