Files
matrixmania/compute.py
T

104 lines
2.8 KiB
Python

import math
def matmul(matrix_a:list[list[float]], matrix_b: list[list[float]]) -> list[list[float]]:
"""
Add two numbers together.
:param matrix_a: The first Matrix
:type matrix_a: list[list[float]]
:param matrix_b: The second Matrix
:type matrix_b: list[list[float]]
:return: The Matrix Multiplication of matrix_a and matrix_b
:rtype: list[list[float]]
"""
try:
if len(matrix_a[0]) != len(matrix_b):
raise ValueError("Differing Matrix Size")
target_height = len(matrix_a)
target_width = len(matrix_b[0])
end_matrix : list[list[float]]= []
for height in range(target_height):
end_matrix.append([])
for width in range(target_width):
row = matrix_a[height]
column_ = []
for b in matrix_b:
column_.append(b[width])
result_quarter = 0
for i in range(len(row)):
result_quarter += row[i] * column_[i]
end_matrix[height].append(float(result_quarter))
return end_matrix
except ValueError:
print("An Error has occurred")
except IndexError:
print("Tried to call non-existing Index")
except TypeError:
print("Tried to insert not a Number")
def transpose(matrix:list[list[float]]) -> list[list[float]]:
"""
Transposes a matrix.
:param matrix: The Matrix, that will be transposed
:type matrix: list[list[float]]
:return: The transposed matrix
:rtype: list[list[float]]
"""
transposed_matrix = []
for x in range(len(matrix[0])):
column = []
for b in matrix:
column.append(b[x])
transposed_matrix.append(column)
return transposed_matrix
def rot_2d(angle:float) -> list[list[float]]:
"""
Creates a Rotation Matrix out of the given angle
:param angle: The rotation in radians
:type angle: float
:return: The Rotation Matrix
:rtype: list[list[float]]
"""
sin = round(math.sin(angle), 4)
cos = round(math.cos(angle), 4)
return [[cos, -sin],
[sin, cos]]
def print_matrix(matrix:list[list[float]]) -> None:
for row in matrix:
print(row)
if __name__ == "__main__":
matrix_bsp_a = [[1, 2, 3], [4, 5, 6]]
matrix_bsp_b = [[1, 2], [3, 4], [5, 6]]
matrix_bsp_c = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix_bsp_d = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
if False:
matrix_bsp_result = matmul(matrix_bsp_c, matrix_bsp_d)
print_matrix(matrix_bsp_result)
if False:
matrix_bsp_result = transpose(matrix_bsp_d)
#print_matrix(matrix_bsp_c)
print_matrix(matrix_bsp_result)
if True:
print_matrix(rot_2d(math.pi*.25))
# Test Kommenter
print("Done")