[Numpy-discussion] product of arrays of different lengths

Francesc Alted faltet@pytables....
Mon Sep 15 05:25:27 CDT 2008

A Monday 15 September 2008, SimonPalmer escrigué:
> 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.

If I understand you correctly, maybe the next is what you want:

max_idx = min(len(A), len(B))
(A[:max_idx] * B[:max_idx]).sum()

which does not require a copy becuase the [:max_idx] operator returns 
just a view of the arrays.

Hope that helps,

Francesc Alted

More information about the Numpy-discussion mailing list