[Numpy-discussion] matrices and __radd__

Keith Goodman kwgoodman@gmail....
Wed May 21 17:28:01 CDT 2008


I have a class that stores some of its data in a matrix. I can't
figure out how to do right adds with a matrix. Here's a toy example:

class Myclass(object):

    def __init__(self, x, a):
        self.x = x  # numpy matrix
        self.a = a  # some attribute, say, an integer

    def __add__(self, other):
        # Assume other is a numpy matrix
        return Myclass(self.x + other, self.a += 1)

    def __radd__(self, other):
        print other

>> from myclass import Myclass
>> import numpy.matlib as mp
>> m = Myclass(mp.zeros((2,2)), 1)
>> x = mp.asmatrix(range(4)).reshape(2,2)
>> radd = x + m
0
1
2
3

The matrix.__add__ sends one element at a time. That sounds slow. Do I
have to grab the corresponding element of self.x and add it to the
element passed in by matrix.__add__? Or is there a better way?


More information about the Numpy-discussion mailing list