Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MatrixError(Exception):
- def __init__(self, text):
- MatrixError.txt = text
- class Mat:
- def __init__(self, n, m, array):
- self.n = n
- self.m = m
- self.a = array
- def __add__(self, other):
- if self.n != other.n or self.m != other.m:
- raise MatrixError("Matrices are of different sizes!")
- for i in range(self.n):
- for j in range(self.m):
- other.a[i][j] += self.a[i][j]
- return other
- def __sub__(self, other):
- if self.n != other.n or self.m != other.m:
- raise MatrixError("Matrices are of different sizes!")
- for i in range(self.n):
- for j in range(self.m):
- other.a[i][j] = self.a[i][j] - other.a[i][j]
- return other
- def __mul__(self, mat):
- if isinstance(mat, int):
- res = [[0 for i in range(self.m)] for j in range(self.n)]
- for i in range(self.n):
- for j in range(self.m):
- res[i][j] = self.a[i][j] * mat
- return Mat(self.n, self.m, res)
- if self.m != mat.n:
- raise MatrixError("Unable to multiply matrices")
- res = [[0 for i in range(mat.m)] for j in range(self.n)]
- for i in range(self.n):
- for j in range(self.m):
- for k in range(mat.m):
- res[i][k] += self.a[i][j] * mat.a[j][k]
- return Mat(self.n, mat.m, res)
- def transponsed(self):
- out = []
- for i in range(self.m):
- rw = []
- for j in range(self.n):
- rw.append(self.a[j][i])
- out.append(rw)
- res = Mat(self.m, self.n, out)
- return res
- def trace(self):
- s = 0
- for i in range(self.n):
- s += self.a[i][i]
- return s
- def print(self):
- for i in range(self.n):
- print(*self.a[i])
- '''
- a = [
- [4, 5, 3],
- [2, -5, 1]
- ]
- b = [
- [-6, -3, 4],
- [5, -1, 6]
- ]
- c = [
- [4, 3],
- [-1, -2]
- ]
- d = [
- [-6, -2],
- [4, 6]
- ]
- '''
- a = [
- [-3, -6, -5],
- [1, 2, 2]
- ]
- b = [
- [5, 2, 6],
- [4, 3, 1]
- ]
- c = [
- [5, -5],
- [-4, 3]
- ]
- d = [
- [-3, 3],
- [-6, 5]
- ]
- A = Mat(2, 3, a)
- B = Mat(2, 3, b)
- C = Mat(2, 2, c)
- D = Mat(2, 2, d)
- R = C * 2 * B * B.transponsed() + (A - B) * (A.transponsed() * A).trace() * (A.transponsed() + B.transponsed()) + C * C * 4 - C * 8 * D + D * D * 4
- #R = D * 4 * A * A.transponsed() + (A + B) * (B.transponsed() * B).trace() * (A.transponsed() - B.transponsed()) - C * C * 2 + C * 4 * D - D * D * 2
- R.print()
Advertisement
Add Comment
Please, Sign In to add comment