Skip to content Skip to sidebar Skip to footer

How To Implement Addition To All Submatrix Elements?

I'm trying to implement matrix class for simple operations with plain python (no numpy and etc.). Here is part of it: class Matrix(list): def __getitem__(self, item): t

Solution 1:

First, inheriting from list is a bad move here. A matrix doesn't support the kinds of operations a list does; for example, you can't append to or extend a matrix, and item assignment is completely different. Your matrix should contain a list, not be a list.

As for what magic methods you need, m[0:2, 0:2] += 1 roughly translates to the following:

temp = m.__getitem__((slice(0, 2), slice(0, 2)))
temp = operator.iadd(temp, 1)
m.__setitem__((slice(0, 2), slice(0, 2)), temp)

where operator.iadd tries temp.__iadd__, temp.__add__, and (1).__radd__ to perform the addition.

You need to implement __getitem__ and __setitem__ to retrieve the submatrix and assign the new submatrix. Additionally, __getitem__ will need to return a matrix, rather than a list.

You should probably implement both __add__ and __iadd__; while __add__ alone would be sufficient for this case, __iadd__ will be necessary for operations like m += 1 to work in-place instead of replacing m with a new matrix object.

Solution 2:

NO. __iadd__ will do the trick for you if the magic was:

m += 2

But the magic is executed over m[0:2, 0:2]. You need to ensure that when slicing your matrix you get a different object, and not a list of lists, since list of lists do not support __iadd__.

Post a Comment for "How To Implement Addition To All Submatrix Elements?"