__mul__, __rmul__ in matrix-vector multiplication

This is the place for queries that don't fit in any of the other categories.

__mul__, __rmul__ in matrix-vector multiplication

Postby hrs » Mon Sep 30, 2013 8:43 pm

I have a Vector class that defines __mul and _rmul__ for vector-vector and scalar-vector multiplication respectively.
Code: Select all
class Vector(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = -y
        self.z = z

    def __mul__(self, other):
        ''' Elementwise vector multiplication '''
        return Vector(self.x * other.x, self.y * other.y, self.z * other.z)

    def __rmul__(self, other):
        ''' Scalar multiplication '''
        return Vector(self.x * other, self.y * other, self.z * other)


Now I need to add a Matrix class that requires matrix-matrix and matrix-vector multiplication support. Is this possible with operator overloading? Would it be acceptable to do something like
Code: Select all
class Matrix(object):
    def __init__(self, x1, y1, z1, x2, y2, z2, x3, y3, z3):
        ...

    def __mul__(self, other):
        if isinstance(other, Vector):
            ...
        elif isinstance(other, Matrix):
            ...
hrs
 
Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm

Re: __mul__, __rmul__ in matrix-vector multiplication

Postby micseydel » Mon Sep 30, 2013 8:59 pm

When type checking is necessary, isinstance() is the proper way to go about it. However, vectors are just a special case of matrixes, so there is probably a more generic way to do this. That said, if I saw the code you've seen here in production code, I wouldn't bat an eye at it. I would encourage you to seek the more generic method though and ask questions if you can't figure it out. (Hint: you'll get arbitrary dimensions for free if you do it.)
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 1116
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: __mul__, __rmul__ in matrix-vector multiplication

Postby hrs » Mon Sep 30, 2013 10:27 pm

Thanks micseydel, I'll take your advise and seek out the generic method.
hrs
 
Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests