[Numpy-discussion] Simple multi-arg wrapper for dot()
Fri Mar 23 23:35:07 CDT 2007
On 24/03/07, Bill Baxter <firstname.lastname@example.org> wrote:
> I mentioned in another thread Travis started on the scipy list that I
> would find it useful if there were a function like dot() that could
> multiply more than just two things.
> Here's a sample implementation called 'mdot'.
> mdot(a,b,c,d) ==> dot(dot(dot(a,b),c),d)
> mdot(a,(b,c),d) ==> dot(dot(a,dot(b,c),d)
> mdot(a,(b,(c,d))) ==> dot(a,dot(b,dot(c,d))
> def mdot(*args):
> """Multiply all the arguments using matrix product rules.
> The output is equivalent to multiplying the arguments one by one
> from left to right using dot().
> Precedence can be controlled by creating tuples of arguments,
> for instance mdot(a,((b,c),d)) multiplies a (a*((b*c)*d)).
> Note that this means the output of dot(a,b) and mdot(a,b) will differ if
> a or b is a pure tuple of numbers.
> if len(args)==1:
> return args
> elif len(args)==2:
> return _mdot_r(args,args)
> return _mdot_r(args[:-1],args[-1])
> def _mdot_r(a,b):
> """Recursive helper for mdot"""
> if type(a)==types.TupleType:
> if len(a)>1:
> a = mdot(*a)
> a = a
> if type(b)==types.TupleType:
> if len(b)>1:
> b = mdot(*b)
> b = b
> return numpy.dot(a,b)
You can do better:
In : from numpy import *
In : a = array([[0,-1],[1,0]])
In : reduce(dot,(a,a,a,a))
In : def mdot(*args):
...: return reduce(dot,args)
In : mdot(a,a,a,a)
Not every two-line Python function has to come pre-written
P.S. reduce isn't even a numpy thing, it's one of python's
much-neglected lispy functions.
More information about the Numpy-discussion