Files
matrixmania/compute.py
T

156 lines
3.9 KiB
Python
Raw 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 typing import TypeAlias
from math import cos, sin
# Funktionen für Matrixberechnungen
Number: TypeAlias = int | float
Matrix: TypeAlias = list[list[Number]]
def matmul(A: Matrix, B: Matrix) -> Matrix:
"""
Multipliziert zwei Matrizen miteinander.
Args:
A: Die erste Matrix.
B: Die zweite Matrix.
Returns:
Die Ergebnismatrix des Produkts.
Raises:
ValueError: Wenn eine Matrix leer oder nicht rechteckig ist
oder die Dimensionen nicht zusammenpassen.
"""
if not A or not B:
raise ValueError("Matrizen dürfen nicht leer sein.")
if not A[0] or not B[0]:
raise ValueError("Matrizen müssen mindestens eine Spalte haben.")
cols_A = len(A[0])
cols_B = len(B[0])
if any(len(row) != cols_A for row in A):
raise ValueError("Matrix A ist nicht rechteckig.")
if any(len(row) != cols_B for row in B):
raise ValueError("Matrix B ist nicht rechteckig.")
if cols_A != len(B):
raise ValueError(
"Die Spaltenzahl von A muss der Zeilenzahl von B entsprechen."
)
rows_A = len(A)
rows_B = len(B)
result: Matrix = [
[0 for _ in range(cols_B)]
for _ in range(rows_A)
]
for i in range(rows_A):
for j in range(cols_B):
for k in range(rows_B):
result[i][j] += A[i][k] * B[k][j]
return result
def transpose(matrix: Matrix) -> Matrix:
"""Return the transpose of a matrix.
Parameters
----------
matrix : List[List[Number]]
Matrix to transpose.
Returns
-------
List[List[Number]]
Transposed matrix where rows become columns.
Raises
------
ValueError
If the input matrix is empty or not rectangular.
"""
if not matrix:
raise ValueError("Cannot transpose an empty matrix.")
n_rows = len(matrix)
n_cols = len(matrix[0])
if any(len(row) != n_cols for row in matrix):
raise ValueError("Input matrix is not rectangular.")
return [[matrix[i][j] for i in range(n_rows)] for j in range(n_cols)]
def rotate_matrix(matrix: Matrix) -> None:
"""Rotiert eine quadratische Matrix 90° im Uhrzeigersinn in‑Place.
Das Verfahren kombiniert Transponieren und Zeilendrehen, was in O(n²) Zeit und O(1) zusätzlichem Speicher arbeitet.
Parameters
----------
matrix : Matrix
Quadratische Matrix, die geändert wird.
Raises
------
ValueError
Wenn die Matrix leer oder nicht quadratisch ist.
"""
n = len(matrix)
if n == 0:
raise ValueError("Matrix darf nicht leer sein.")
for row in matrix:
if len(row) != n:
raise ValueError("Matrix muss quadratisch sein.")
# Transpose
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse rows
for row in matrix:
row.reverse()
def rot_2D(theta: float) -> Matrix:
"""
Erstellt eine Rotationsmatrix für eine Drehung in 2D.
Args:
theta: Drehwinkel im Bogenmaß.
Returns:
Eine 2x2-Rotationsmatrix.
"""
return [
[cos(theta), -sin(theta)],
[sin(theta), cos(theta)]
]
if __name__ == "__main__":
# Beispiel Multiplikation
A1 = [[1, 2, 3], [4, 5, 6]]
B1 = [[7, 8], [9, 10], [11, 12]]
expected1 = [[58, 64], [139, 154]]
assert matmul(A1, B1) == expected1
print("Beispiel 1 erfolgreich:", matmul(A1, B1))
#Beispiel Rotation
matrix = [[1, 2], [3, 4]]
expected = [[3, 1], [4, 2]]
rotate_matrix(matrix)
assert matrix == expected
print("Rotation erfolgreich:", matrix)
#Beispiel Transponierung
matrix = [[1, 2, 3], [4, 5, 6]]
expected = [[1, 4], [2, 5], [3, 6]]
assert transpose(matrix) == expected
print("Transponierung erfolgreich:", transpose(matrix))