2025-12-09 14:20:13 +01:00

126 lines
3.2 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
from math import cos, sin
from typing import List
def rot_3D(angle: float, axis: str) -> List[List[float]]:
"""
Berechnet die 3x3-Rotationsmatrix für eine Rotation im 3D-Raum.
Die Rotationsmatrizen lauten:
Rotation um die x-Achse:
Rx(θ) = [[1, 0, 0],
[0, cos θ, -sin θ],
[0, sin θ, cos θ]]
Rotation um die y-Achse:
Ry(θ) = [[ cos θ, 0, sin θ],
[ 0, 1, 0],
[-sin θ, 0, cos θ]]
Rotation um die z-Achse:
Rz(θ) = [[cos θ, -sin θ, 0],
[sin θ, cos θ, 0],
[ 0, 0, 1]]
:param angle: Rotationswinkel in Radiant.
:param axis: Rotationsachse: 'x', 'y' oder 'z' (Groß-/Kleinschreibung egal).
:return: 3x3-Rotationsmatrix als verschachtelte Liste.
:raises ValueError: Wenn axis nicht 'x', 'y' oder 'z' ist.
"""
a = axis.lower()
c = cos(angle)
s = sin(angle)
if a == "x":
return [
[1.0, 0.0, 0.0],
[0.0, c, -s ],
[0.0, s, c ],
]
if a == "y":
return [
[c, 0.0, s ],
[0.0, 1.0, 0.0],
[-s, 0.0, c ],
]
if a == "z":
return [
[c, -s, 0.0],
[s, c, 0.0],
[0.0, 0.0, 1.0],
]
raise ValueError("axis must be 'x', 'y' or 'z'")
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)