# [Numpy-discussion] efficient summation

Paulo J. S. Silva rsilva at ime.usp.br
Wed Sep 1 19:19:05 EDT 2004

```Em Qua, 2004-09-01 às 18:51, Darren Dale escreveu:
> I am trying to effieciently sum over a subset of the elements of a
> matrix. In Matlab, this could be done like:
> a=[1,2,3,4,5,6,7,8,9,10]
> b = [1,0,0,0,0,0,0,0,0,1]
> res=sum(a(b)) %this sums the elements of a which have corresponding
> elements in b that are true

If the mask is of boolean type (not integer) you can use it just like in
MATLAB:

>>> from numarray import *
>>> import numarray.random_array as ra
>>> a = ra.random(1000000)
>>> sum(a)
500184.16988508566
>>> b = ra.random(1000000) < 0.1
>>> sum(a[b])
50331.373006955822

This should work for numarray only.

Paulo

--
Paulo José da Silva e Silva
Professor Assistente do Dep. de Ciência da Computação
(Assistant Professor of the Computer Science Dept.)
Universidade de São Paulo - Brazil

e-mail: rsilva at ime.usp.br           Web: http://www.ime.usp.br/~rsilva
Teoria é o que não entendemos o     (Theory is something we don't)
suficiente para chamar de prática.  (understand well enough to call
practice)

```