MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / Matrix

Class Matrix

linear_algebra/src/lib.py:243–424  ·  view source on GitHub ↗

class: Matrix This class represents an arbitrary matrix. Overview of the methods: __init__(): __str__(): returns a string representation __add__(other: Matrix): matrix addition __sub__(other: Matrix): matrix subtraction __mul__(other: float): sc

Source from the content-addressed store, hash-verified

241
242
243class Matrix:
244 """
245 class: Matrix
246 This class represents an arbitrary matrix.
247
248 Overview of the methods:
249
250 __init__():
251 __str__(): returns a string representation
252 __add__(other: Matrix): matrix addition
253 __sub__(other: Matrix): matrix subtraction
254 __mul__(other: float): scalar multiplication
255 __mul__(other: Vector): vector multiplication
256 height() : returns height
257 width() : returns width
258 component(x: int, y: int): returns specified component
259 change_component(x: int, y: int, value: float): changes specified component
260 minor(x: int, y: int): returns minor along (x, y)
261 cofactor(x: int, y: int): returns cofactor along (x, y)
262 determinant() : returns determinant
263 """
264
265 def __init__(self, matrix: list[list[float]], w: int, h: int) -> None:
266 """
267 simple constructor for initializing the matrix with components.
268 """
269 self.__matrix = matrix
270 self.__width = w
271 self.__height = h
272
273 def __str__(self) -> str:
274 """
275 returns a string representation of this matrix.
276 """
277 ans = ""
278 for i in range(self.__height):
279 ans += "|"
280 for j in range(self.__width):
281 if j < self.__width - 1:
282 ans += str(self.__matrix[i][j]) + ","
283 else:
284 ans += str(self.__matrix[i][j]) + "|\n"
285 return ans
286
287 def __add__(self, other: Matrix) -> Matrix:
288 """
289 implements matrix addition.
290 """
291 if self.__width == other.width() and self.__height == other.height():
292 matrix = []
293 for i in range(self.__height):
294 row = [
295 self.__matrix[i][j] + other.component(i, j)
296 for j in range(self.__width)
297 ]
298 matrix.append(row)
299 return Matrix(matrix, self.__width, self.__height)
300 else:

Callers 15

__add__Method · 0.70
__sub__Method · 0.70
__mul__Method · 0.70
minorMethod · 0.70
square_zero_matrixFunction · 0.70
random_matrixFunction · 0.70
test_str_matrixMethod · 0.70
test_minorMethod · 0.70
test_cofactorMethod · 0.70
test_determinantMethod · 0.70
test__mul__matrixMethod · 0.70

Calls

no outgoing calls

Tested by 9

test_str_matrixMethod · 0.56
test_minorMethod · 0.56
test_cofactorMethod · 0.56
test_determinantMethod · 0.56
test__mul__matrixMethod · 0.56
test_component_matrixMethod · 0.56
test__add__matrixMethod · 0.56
test__sub__matrixMethod · 0.56