135 lines
3.5 KiB
Python
135 lines
3.5 KiB
Python
"""Utilities for numeric matrix operations.
|
|
|
|
This module provides matrix helpers (matmul, transpose, rot_2D)
|
|
for the MatrixMania project.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from math import cos, sin
|
|
from typing import List
|
|
|
|
from tabulate import tabulate
|
|
|
|
Matrix = List[List[float]]
|
|
|
|
|
|
def matmul(a: Matrix, b: Matrix) -> Matrix:
|
|
"""Return the product of two matrices.
|
|
|
|
Parameters
|
|
----------
|
|
a: list[list[float]]
|
|
Left matrix of shape ``(m, n)``.
|
|
b: list[list[float]]
|
|
Right matrix of shape ``(n, p)``.
|
|
|
|
Returns
|
|
-------
|
|
list[list[float]]
|
|
Resultant matrix of shape ``(m, p)``.
|
|
"""
|
|
if not isinstance(a, list) or not isinstance(b, list):
|
|
raise ValueError("Both arguments must be 2-D lists of numbers.")
|
|
|
|
if not a or not a[0] or not b or not b[0]:
|
|
raise ValueError("Matrices must be non-empty and properly sized.")
|
|
|
|
a_rows, a_cols = len(a), len(a[0])
|
|
b_rows, b_cols = len(b), len(b[0])
|
|
|
|
if any(len(row) != a_cols for row in a):
|
|
raise ValueError("All rows in matrix 'a' must have the same length.")
|
|
if any(len(row) != b_cols for row in b):
|
|
raise ValueError("All rows in matrix 'b' must have the same length.")
|
|
if a_cols != b_rows:
|
|
raise ValueError(
|
|
f"Inner dimensions mismatch: "
|
|
f"a has {a_cols} columns, b has {b_rows} rows."
|
|
)
|
|
|
|
b_t = list(map(list, zip(*b)))
|
|
|
|
result: Matrix = []
|
|
for row_a in a:
|
|
res_row: List[float] = []
|
|
for col_b in b_t:
|
|
dot = sum(x * y for x, y in zip(row_a, col_b))
|
|
res_row.append(dot)
|
|
result.append(res_row)
|
|
return result
|
|
|
|
|
|
def transpose(matrix: Matrix) -> Matrix:
|
|
"""Return the transpose of a 2-D list.
|
|
|
|
Parameters
|
|
----------
|
|
matrix: list[list[float]]
|
|
The matrix to transpose. All rows must have equal length.
|
|
|
|
Returns
|
|
-------
|
|
list[list[float]]
|
|
The transposed matrix.
|
|
"""
|
|
if not isinstance(matrix, list) or not matrix:
|
|
raise ValueError("Matrix must be a non-empty 2-D list.")
|
|
if any(not isinstance(row, list) for row in matrix):
|
|
raise ValueError("Matrix must contain rows that are lists.")
|
|
row_len = len(matrix[0])
|
|
if any(len(row) != row_len for row in matrix):
|
|
raise ValueError("All rows in the matrix must have the same length.")
|
|
return list(map(list, zip(*matrix)))
|
|
|
|
|
|
def rot_2D(winkel: float) -> Matrix:
|
|
"""Return the 2-D rotation matrix for an angle in radians.
|
|
|
|
Parameters
|
|
----------
|
|
winkel: float
|
|
Rotation angle in radians. Positive values rotate
|
|
counter-clockwise.
|
|
|
|
Returns
|
|
-------
|
|
list[list[float]]
|
|
The 2x2 rotation matrix.
|
|
"""
|
|
return [[cos(winkel), -sin(winkel)], [sin(winkel), cos(winkel)]]
|
|
|
|
|
|
def print_matrix(matrix: Matrix) -> None:
|
|
"""Print a matrix as a nicely formatted table."""
|
|
print(tabulate(matrix, tablefmt="grid"))
|
|
|
|
def rot_3D(angle: float, axis: str) -> list[list[float]]:
|
|
axis = axis.lower()
|
|
c, s = cos(angle), sin(angle)
|
|
|
|
if axis == "x":
|
|
return [[1.0, 0.0, 0.0],
|
|
[0.0, c, -s],
|
|
[0.0, s, c]]
|
|
if axis == "y":
|
|
return [[c, 0.0, s],
|
|
[0.0, 1.0, 0.0],
|
|
[-s, 0.0, c]]
|
|
if axis == "z":
|
|
return [[c, -s, 0.0],
|
|
[s, c, 0.0],
|
|
[0.0, 0.0, 1.0]]
|
|
|
|
raise ValueError(f"Invalid axis '{axis}': expected 'x', 'y' or 'z'.")
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
a = [[1, 2], [3, 4]]
|
|
b = [[5, 6], [7, 8]]
|
|
print_matrix(matmul(a, b))
|
|
print_matrix(rot_2D(1.0))
|
|
|