70 lines
1.8 KiB
Python
70 lines
1.8 KiB
Python
from typing import List
|
|
|
|
def matmul(A: List[List[float]], B: List[List[float]]) -> List[List[float]]:
|
|
"""
|
|
Multiplies two matrices A and B (nested Python lists).
|
|
|
|
Requirements:
|
|
- A has shape (m x n), B has shape (n x p).
|
|
- All rows in A and B must have equal length.
|
|
- Elements are numeric (float/int).
|
|
|
|
Args:
|
|
A: Left matrix, list of rows (m x n).
|
|
B: Right matrix, list of rows (n x p).
|
|
|
|
Returns:
|
|
New matrix C = A * B with shape (m x p).
|
|
|
|
Raises:
|
|
ValueError: If matrices are empty, ragged,
|
|
or shapes are incompatible.
|
|
|
|
"""
|
|
if not A or not B:
|
|
raise ValueError("Empty matrices are not supported.")
|
|
if not A[0] or not B[0]:
|
|
raise ValueError("Matrices must have at least one column.")
|
|
|
|
a_cols = len(A[0])
|
|
|
|
for row in A:
|
|
if len(row) != a_cols:
|
|
raise ValueError("Left matrix has inconsistent row lengths.")
|
|
b_cols = len(B[0])
|
|
for row in B:
|
|
if len(row) != b_cols:
|
|
raise ValueError("Right matrix has inconsistent row lengths.")
|
|
|
|
if a_cols != len(B):
|
|
raise ValueError(
|
|
f"Incompatible shapes: A is {len(A)}x{a_cols}, "
|
|
f"B is {len(B)}x{b_cols}; need cols(A) == rows(B)."
|
|
)
|
|
|
|
m, n, p = len(A), a_cols, b_cols
|
|
C: List[List[float]] = [[0 for _ in range(p)] for _ in range(m)]
|
|
|
|
for i in range(m):
|
|
for k in range(n):
|
|
a_ik = A[i][k]
|
|
for j in range(p):
|
|
C[i][j] += a_ik * B[k][j]
|
|
|
|
return C
|
|
|
|
|
|
if __name__ == "__main__":
|
|
matrix_a = [[3, 4, -1, 4],
|
|
[-2, 2, 5, 1]]
|
|
matrix_b = [[1, 3, -2],
|
|
[2, 5, 1],
|
|
[-1, 4, -4],
|
|
[2, 3, 6]]
|
|
matrix_c = matmul(matrix_a, matrix_b)
|
|
print("Ergebnis C = A * B:")
|
|
for row in matrix_c:
|
|
print(row)
|
|
|
|
|