1
0

Finalize matrix.py

This commit is contained in:
2024-01-13 12:55:34 +01:00
parent b9c03b5d5f
commit 0450811b0c
2 changed files with 195 additions and 18 deletions

View File

@ -1,4 +1,5 @@
import numpy
from numpy import linalg
class Matrix:
@ -47,7 +48,8 @@ class Matrix:
elif structure == "tridiagonal":
if len(data) != 3:
raise ValueError("If structure is tridiagonal, then the given data must be of length 3")
tridiag = numpy.diag([data[0]] * (n-1), -1) + numpy.diag([data[1]] * n, 0) + numpy.diag([data[2]] * (n-1), 1)
tridiag = numpy.diag([data[0]] * (n - 1), -1) + numpy.diag([data[1]] * n, 0) + numpy.diag(
[data[2]] * (n - 1), 1)
self.__data__ = tridiag
self.__shape__ = tridiag.shape
# Case: Matrix(list, str, int)
@ -64,7 +66,8 @@ class Matrix:
self.__shape__ = data.shape
self.__data__ = data
else:
raise ValueError("Only following signatures are allowed: (numpy.ndarray), (list, tuple), (list, str, int), (str, int)")
raise ValueError(
"Only following signatures are allowed: (numpy.ndarray), (list, tuple), (list, str, int), (str, int)")
def get_data(self):
"""
@ -126,16 +129,47 @@ class Matrix:
def __rsub__(self, other):
return -self + other
def __mul__(self, other):
if isinstance(other, Matrix):
if self.__shape__[1] != other.__shape__[0]:
raise ValueError(
"The amount of columns of the first operand must match the amount of rows of the second operand")
return Matrix(self.__data__ @ other.__data__)
elif isinstance(other, int) or isinstance(other, float):
return Matrix(other * self.__data__)
else:
raise ValueError("Only a number or another ``Matrix`` can be multiplied to a ``Matrix``")
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if isinstance(other, int) or isinstance(other, float):
return self.__data__ / other
else:
raise ValueError("A ``Matrix`` can only be divided ba a number")
def __mul__(self, other):
if isinstance(other, Matrix):
if self.__shape__[1] != other.__shape__[0]:
raise ValueError("The amount of columns of the first operand must match the amount of rows of the second operand")
return Matrix(self.__data__ * other.__data__)
elif isinstance(other, int) or isinstance(other, float):
...
def norm(self, f: str = "frobenius"):
"""
Calculates the norm of the matrix.
A norm is a positive definit, absolute homogeneous and subadditive function.
For Matrices a norm is also sub-multiplicative.
:param f: The norm to be used, could be either "frobenius", "rowsum" or "colsum"
:return: the norm as a number
"""
t = "fro"
if f == "colsum":
t = 1
elif f == "rowsum":
t = numpy.inf
return linalg.norm(self.__data__, t)
def __getitem__(self, key):
return self.__data__[key]
def __setitem__(self, key, value):
self.__data__[key] = value