[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Vectorization question



"Liam E. Gumley" wrote:
> 
> Given the following arrays
> 
> a = intarr(10)
> x = [2, 2, 2, 3, 3, 4]
> b = [1, 3, 4, 2, 1, 8]
> 
> How would I vectorize the following operation
> 
> for i = 0, n_elements(x) - 1 do a[x[i]] = a[x[i]] + b[i]
> 
> To achieve this result
> 
> print, a, format='(10i4)'
>    0   0   8   3   8   0   0   0   0   0
> 
> In the real-world case where this occurs, I need to repeat this kind of
> operation several hundred times, where the size of 'a' is around
> 1,000,000 and the size of 'x' is around 100,000 ('a' and 'b' are float
> type in the real-world case).

Here's one solution:

a = intarr(10)
x = [2, 2, 2, 3, 3, 4]
b = [1, 3, 4, 2, 1, 8]
tmp = intarr(n_elements(a), n_elements(x))
tmp[x, indgen(n_elements(x))] = b
print, a + total(tmp, 2), format='(10i4)'
   0   0   8   3   8   0   0   0   0   0

It's a bit memory hungry, but it's fast. Any other offers?

Cheers,
Liam.