Why doesn't numpy throw an error when you do something like
np.ones((5,5)) + np.ones(5)
Such addition is not clearly defined in linear algebra, and it just took me several hours to track down a bug that boiled down to this
np.ones((5,5)) + np.ones(5)
np.ones((5,5)) + np.ones(4) <- This would give a error.
since np.ones(5) fit the size of each row it will to a element wise addition to each row.
That's simply how numpy works. I's is not a linear algebra module.
Here is a short example of how you could do it, this does need to be extended, with more logic and cleverness. Just a proof of concept.
import numpy as np
class myMatrixClass(np.ndarray):
    def __add__(self,val):
        if (hasattr(val, '__iter__') and self.shape != val.shape):
            print "not valid addition!"
        else:
            return super(myMatrixClass, self).__add__(val)
In [33]: A = myMatrixClass( shape=(5,5))
In [34]: A[:] = 1
In [35]: B = A + 1
In [36]: B
Out[36]:
myMatrixClass([[ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.,  2.]])
In [37]: C = A + np.ones(5)
not valid addition!
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With