Files
2026-11-12 14:26:07 +01:00

162 lines
4.1 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.
from tabulate import tabulate
Matrix = list[list[int]]
def matmul(matrix_a: Matrix, matrix_b: Matrix) -> Matrix:
"""Return the matrix product of ``matrix_a`` and ``matrix_b``.
Parameters
----------
matrix_a: List[List[int]]
The left‑hand matrix.
matrix_b: List[List[int]]
The right‑hand matrix.
Returns
-------
List[List[int]]
The result of the matrix multiplication.
Raises
------
ValueError
If the number of columns in ``matrix_a`` does not match the number of
rows in ``matrix_b``.
"""
if not matrix_a or not matrix_b:
raise ValueError("Both matrices must be non‑empty")
# Validate matrix shapes.
rows_a, cols_a = len(matrix_a), len(matrix_a[0])
rows_b, cols_b = len(matrix_b), len(matrix_b[0])
if cols_a != rows_b:
raise ValueError(
f"Incompatible dimensions: matrix_a has {cols_a} columns, "
f"matrix_b has {rows_b} rows"
)
# Confirm consistency of each row (rectangular matrices).
if any(len(row) != cols_a for row in matrix_a):
raise ValueError("matrix_a rows must all have the same length")
if any(len(row) != cols_b for row in matrix_b):
raise ValueError("matrix_b rows must all have the same length")
result: Matrix = []
for i in range(rows_a):
result_row = []
for j in range(cols_b):
val = 0
for k in range(cols_a):
val += matrix_a[i][k] * matrix_b[k][j]
result_row.append(val)
result.append(result_row)
return result
# Import for trigonometric functions
import math
def matvec(a: Matrix, v: list[float]) -> list[float]:
"""Return the product of a matrix and a column vector.
Parameters
----------
a: list[list[float]]
Matrix of shape ``(m, n)``.
v: list[float]
Column vector of shape ``(n,)``.
Returns
-------
list[float]
Resulting vector of shape ``(m,)``.
"""
if not isinstance(a, list) or not isinstance(v, list):
raise TypeError("Matrix and vector must be lists of numbers.")
if not a or not a[0] or not v:
raise ValueError("Matrix and vector must be non-empty.")
if any(len(row) != len(v) for row in a):
raise ValueError(f"Inner dimensions mismatch: vector has {len(v)} entries.")
return [sum(x * y for x, y in zip(row, v)) for row in a]
def rot_2D(theta: float) -> Matrix:
"""Return a 2×2 rotation matrix for the given angle ``theta``.
Parameters
----------
theta : float
Rotation angle in **radians**.
Returns
-------
List[List[float]]
``[[cos(theta), -sin(theta)], [sin(theta), cos(theta)]]``.
Notes
-----
The returned values are floating point numbers because trigonometric
functions are used.
"""
c = math.cos(theta)
s = math.sin(theta)
return [[c, -s], [s, c]]
def transpose(matrix: Matrix) -> Matrix:
"""Return the transpose of ``matrix``.
Transposes rows and columns.
Parameters
----------
matrix : List[List[int]]
The matrix to transpose.
Returns
-------
List[List[int]]
The transposed matrix.
Raises
------
ValueError
If the matrix is empty or rows have inconsistent length.
"""
if not matrix:
raise ValueError("Matrix must not be empty")
rows, cols = len(matrix), len(matrix[0])
if any(len(row) != cols for row in matrix):
raise ValueError("matrix rows must all have the same length")
return [[matrix[r][c] for r in range(rows)] for c in range(cols)]
# Rest of module.
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)
print("\nTransponierte Matrix A:")
for row in transpose(matrix_a):
print(row)
print("\nRotierte Matrix (90°):")
for row in rot_2D(math.pi/2):
print(row)
print(tabulate(rot_2D(1.0)))
#test git kommentar