Skip to content

Instantly share code, notes, and snippets.

@morganwilde
Last active August 29, 2015 14:18
Show Gist options
  • Save morganwilde/470a5d677976cc793a63 to your computer and use it in GitHub Desktop.
Save morganwilde/470a5d677976cc793a63 to your computer and use it in GitHub Desktop.
class Matrix():
def __init__(self, width, height):
self.width = width
self.height = height
# Initialise the matrix grid
self.matrix = []
for row in range(height):
self.matrix.append([])
for column in range(width):
self.matrix[row].append(0)
def getValue(self, column, row):
if column >= 0 and column < self.width and row >= 0 and row < self.height:
return self.matrix[row][column]
else:
return None
def setValue(self, column, row, value):
self.matrix[row][column] = value
def addWithMatrix(self, matrix):
if self.width == matrix.width and self.height == matrix.height:
for row in range(self.height):
for column in range(self.width):
valueNew = self.getValue(column, row) + matrix.getValue(column, row)
self.setValue(column, row, valueNew)
else:
print "Error: matrix size must be the same!"
matrixA = Matrix(10, 10)
matrixB = Matrix(11, 10)
matrixA.setValue(1, 2, 5)
matrixB.setValue(1, 2, 6)
matrixA.addWithMatrix(matrixB)
print matrixA.getValue(1, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment