Files

178 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Utility module providing basic matrix operations.
Functions
---------
- :func:`matmul` – Multiply two matrices.
- :func:`transpose` – Transpose a matrix.
- :func:`rotate` – Rotate a matrix 90° clockwise.
All functions work on nested Python lists and perform basic
validation before operation.
"""
from __future__ import annotations
Matrix = list[list[float]]
def matmul(a: Matrix, b: Matrix) -> Matrix:
"""Return the product of two matrices.
Parameters
----------
a: Matrix
Left‑hand matrix (shape ``m × n``).
b: Matrix
Right‑hand matrix (shape ``n × p``).
Returns
-------
Matrix
Resulting matrix of shape ``m × p``.
Raises
------
ValueError
If the inner dimensions of the matrices do not match, or if
either argument is empty.
"""
if not a or not a[0] or not b or not b[0]:
raise ValueError("Input matrices must be non‑empty")
n_cols_a = len(a[0])
n_rows_b = len(b)
if n_cols_a != n_rows_b:
raise ValueError(
f"Inner dimensions must agree for matrix multiplication: "
f"{len(a)}×{n_cols_a} and {n_rows_b}×{len(b[0])}"
)
m = len(a)
p = len(b[0])
result: Matrix = [[0.0 for _ in range(p)] for _ in range(m)]
for i in range(m):
for j in range(p):
total = 0.0
for k in range(n_cols_a):
total += a[i][k] * b[k][j]
result[i][j] = total
return result
def transpose(matrix: Matrix) -> Matrix:
"""Return the transpose of a matrix.
Parameters
----------
matrix: Matrix
A matrix represented as a list of row lists.
Returns
-------
Matrix
The transposed matrix.
Raises
------
ValueError
If the matrix is empty or rows are not of equal length.
"""
if not matrix or not matrix[0]:
raise ValueError("Input matrix must be non‑empty")
row_length = len(matrix[0])
for row in matrix:
if len(row) != row_length:
raise ValueError("All rows in the matrix must have the same length")
return [list(col) for col in zip(*matrix)]
def rot_2d(matrix: Matrix) -> Matrix:
"""Return the matrix rotated 90 degrees clockwise.
This is equivalent to transposing the matrix and then reversing
each row.
Parameters
----------
matrix: Matrix
A matrix represented as a list of row lists.
Returns
-------
Matrix
The rotated matrix.
Raises
------
ValueError
If the matrix is empty or rows are not of equal length.
"""
transposed = transpose(matrix)
return [list(reversed(row)) for row in transposed]
def rot_3d(matrix: Matrix, angle: float, axis: str) -> Matrix:
"""Return a new matrix rotated around the specified axis.
Parameters
----------
matrix: Matrix
Matrix of 3‑element vectors to be rotated.
angle: float
Rotation angle in degrees.
axis: str
Axis to rotate around. Must be ``'x'``, ``'y'`` or ``'z'``.
Returns
-------
Matrix
Rotated matrix of 3‑element vectors.
Raises
------
ValueError
If the input matrix is empty, rows are not of length 3, or the axis is invalid.
"""
import math
if not isinstance(angle, (int, float)):
raise ValueError("angle must be a numeric value")
if not isinstance(axis, str):
raise ValueError("axis must be a string")
rad = math.radians(angle)
c = math.cos(rad)
s = math.sin(rad)
axis = axis.lower()
if axis == "x":
rot = [[1, 0, 0],
[0, c, -s],
[0, s, c]]
elif axis == "y":
rot = [[c, 0, s],
[0, 1, 0],
[-s, 0, c]]
elif axis == "z":
rot = [[c, -s, 0],
[s, c, 0],
[0, 0, 1]]
else:
raise ValueError("axis must be one of 'x', 'y', or 'z'")
if not matrix or not all(isinstance(row, list) for row in matrix):
raise ValueError("Input must be a list of rows")
if not all(len(row) == 3 for row in matrix):
raise ValueError("Each row must contain exactly 3 elements")
result: Matrix = []
for vec in matrix:
if any(not isinstance(v, (int, float)) for v in vec):
raise ValueError("All coordinates must be numeric")
rotated = [sum(v * r for v, r in zip(vec, col)) for col in zip(*rot)]
result.append([float(x) for x in rotated])
return result
"""End of module"""