Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arxcis/af90ead7357c8b8b0fd2999b765e687e to your computer and use it in GitHub Desktop.
Save Arxcis/af90ead7357c8b8b0fd2999b765e687e to your computer and use it in GitHub Desktop.
class Vector:
"""
class -- Represents a Vector with n length
"""
def __init__(self, nparray):
self.array = nparray #1d numpy array
self.length = len(self.array)
self.x = self.array[0]
self.y = self.array[1]
class Matrix:
"""
class -- A class that represents the [n x m] - matrix
"""
def __init__(self, nparray): # nparray should be of type np.array()
self.array = nparray # 2d numpy array
self.height = len(self.array) # n = rows
self.width = len(self.array[0]) # m = columns
self.n = self.height # n = rows
self.m = self.width # m = columns
def __mul__(self, other, debug=True):
"""operator -- Overloading * (multiplication) """
count = 0 # count for debug print
#
# ----- MATRIX * MATRIX ----
#
if type(other) is Matrix:
if self.width == other.height:
result_matrix = np.zeros((self.height, other.width))
for i in range(other.width):
for j in range(self.height):
for k in range(self.width):
result_matrix[j][i] += self.array[j][k] * other.array[k][i]
if debug:
count += 1
print("#", count, ": i:", i, " j:", j, " k:", k)
print(result_matrix)
return Matrix(result_matrix)
else:
print("Wrong dimensions. self.width should be exactly other.height. Returning self.")
return self
#
# ----- MATRIX * VECTOR ----
#
elif type(other) is Vector:
if self.width == other.length:
result_matrix = np.zeros( self.height ) # Creating a 1D - [N x 1] resultant vector
print(result_matrix)
for i in range( self.height ):
for j in range( other.length ):
result_matrix[i] += self.array[i][j] * other.array[j]
if debug:
count += 1
print("#", count, ": i:", i, " j:", j)
print(result_matrix)
return result_matrix
else:
print("Wrong dimensions. self.width should be exactly other.height. Returning self.")
return self
else:
print("Wrong type. Should be Matrix or Vector. Is of: ", type(other),"Returning self.")
return self
def __str__(self):
"""return -- string representation of object"""
return "Matrix with " + str(self.height) + " rows and " + str(self.width) + " columns"
def __repr__(self):
"""return -- string representation of object"""
string = "\n---- " + str(self.height) + " X " + str(self.width) + " ----\n"
for i in range(self.height):
for j in range(self.width):
if self.array[i][j] > 0:
temp = "{0:.3f}".format(self.array[i][j])
string += "{0: >5}".format(temp)
else:
temp = "{0:.0f}".format(self.array[i][j])
string += "{0: >5}".format(temp)
string += "\n"
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment