[Numpy-discussion] product of arrays of different lengths
SimonPalmer
simon.palmer@gmail....
Mon Sep 15 04:55:23 CDT 2008
I have two 1D arrays of different lengths and I want the calculate sum
of the product of the two to the extent of the smaller of them (make
sense?). I don't know which of the two will be the longer ahead of
time.
I expected (hoped) to be able to do this:
sp = (A * B).sum()
and imagined that the trailing end of the longer of the two arrays
might just be ignored, but instead I get an error "objects cannot be
broadcast to a single shape".
Both arrays are generally very short (<100 elements) so I can tolerate
a copy, however this calculation is right in the heart of the
innermost loop in my code, so I have to tread a bit carefully.
Here's what I do at the moment, which is ugly, but works
max_idx = min(len(A), len(B))
total_product = 0
for idx in range(0, max_idx):
total_product += A[idx] * B[idx]
...but this is numpy, so I'm looking for a neat way.
More information about the Numpy-discussion
mailing list