class Matrix:
M = None
N = None
matrix = None
def __init__(self, N, M):
self.N = N
self.M = M
self.matrix = [[0]*M]*N
def setMatrix(self, matrix):
if (self.badMatrix(matrix)):
raise Exception("Error: unmatching dimensions.")
self.matrix = matrix
def toString(self):
for i in range(self.N):
for j in range(self.M):
print(self.matrix[i][j], end=" ")
print()
def plus(self, other):
if (other.N != self.N | other.M != self.M):
raise Exception("Error: cannot add matrices of different dimensions.")
result = Matrix(self.N, self.M)
for i in range(self.N):
for j in range(self.M):
result.matrix[i][j] = self.matrix[i][j] + other.matrix[i][j]
return result
def minus(self, other):
if (other.N != self.N | other.M != self.M):
raise Exception("Error: cannot subtract matrices of different dimensions.")
result = Matrix(self.N, self.M)
for i in range(self.N):
for j in range(self.M):
result.matrix[i][j] = self.matrix[i][j] - other.matrix[i][j]
print(result.matrix[i][j]) #<-- but this gives me correct result... huh?
return result
def badMatrix(self, matrix):
if (len(matrix) != self.N):
return True
for i in range(self.N):
if (len(matrix[i]) != self.M):
return True
return False
from Matrix import *
A = Matrix(3, 3)
A.setMatrix([[1,2,3],
[4,5,6],
[7,8,9]])
B = Matrix(3, 3)
B.setMatrix([[9,8,7],
[6,5,4],
[3,2,1]])
C = A.plus(B)/>
C.toString()
D = A.minus(B)/>
D.toString()
C gives met he correct value, but D doesn't. The plus and minus functions are practically identical... any idea what's wrong?
This post has been edited by carnivroar: 22 July 2012 - 05:40 PM

New Topic/Question
Reply



MultiQuote







|