[SciPy-user] addition of vectors of different lengths

Dan Christensen jdc at uwo.ca
Tue Aug 2 23:00:45 CDT 2005


Here's a bit more information to make my question more specific.
Compare the following:

from numarray import *
import operator

def addarray(v1, v2):
    '''Add two numarrays componentwise, extending by zero if necessary.'''
    l1 = len(v1)
    l2 = len(v2)
    if l1 == l2:
        v = v1+v2
    elif l1 < l2:
        v = concatenate((v1+v2[:l1], v2[l1:]))
    else:
        v = concatenate((v1[:l2]+v2, v1[l2:]))

def addlist(v1, v2):
    '''Add two lists componentwise, extending by zero if necessary.'''
    l1 = len(v1)
    l2 = len(v2)
    if l1 == l2:
        v = map(operator.add, v1, v2)
    elif l1 < l2:
        v = map(operator.add, v1, v2[:l1])+v2[l1:]
    else:
        v = map(operator.add, v1[:l2], v2)+v1[l2:]

l1=range(236)
a1=array(l1)
l2=range(256)
a2=array(l2)

addarray(a1, a2)    126   usec
addarray(a2, a2)     20   usec
addlist(l1, l2)      96.2 usec
addlist(l2, l2)      95.8 usec
          
I'd like the speed of numarray for equal length addition combined
with the way addlist doesn't get much slower with unequal lengths.

Dan



More information about the SciPy-user mailing list