Numerical Python array math with different sized arrays

Michael Weiss FooWeissBarMike at hotmail.com
Mon Jun 24 11:44:49 EDT 2002


I'm using Numeric Python's arrays. I want to perform the various math
operators between arrays (+-*/ etc...) .
While all my arrays are 1 dimensional, they may be different lengths. The
result I'd like in a mis-matched size case is the following:
>>> a = Numeric.array([1,2,3,4])
>>> b = Numeric.array([1,2])
>>> print a+b
[2,4,3,4]

I assume the answer is to resize b, and make the new elements all zero. My
question is what is the fastest way to do this. Resize() does that repeating
thing, which is not what I want (I want zeros in those new elements).

I've tried the following, is there a better way?

#####
lena = len(a)
lenb = len(b)

if lena == lenb:
   numa = Numeric.array(a)
   numb = Numeric.array(b)
elif lena > lenb:
   numa = Numeric.array(a)
   zeros = Numeric.zeros((lena-lenb,))
   numb = Numeric.concatenate((b, zeros, ))
else:
   zeros = Numeric.zeros((lenb-lena,))
   numa = Numeric.concatenate((a, zeros, ))
   numb = Numeric.array(b)

numans = numa+numb
#####






More information about the Python-list mailing list