Incrementing an element multiple times without a loop? [message #88440] |
Fri, 25 April 2014 07:50  |
TimB
Messages: 6 Registered: April 2011
|
Junior Member |
|
|
I'm trying to speed up a process within a nested loop. Essentially I have an array of 0's (array a) and another array which tells which elements of a to increment by +1 (array b).
The element in array a should be incremented the same number of times it is in array b.
For example a = [0,0,0], b=[1,1,2], the result should be [0,2,1]
Simply using a[b]+=1 only increments the each unique element in b once and would give [0,1,1]
The only thing I could come up was
result=uniq(b[sort(b)])
result-=[-1,result[0:n_elements(b)-2]]
but that only works if all of the elements in a are mentioned in b at least once. Here's a small example:
PRO ele_increment
a=intarr(5) ;blank array
b=[0,1,0,3,2,4,4,1,1,2,0,1,1] ;elements in arr to increment by +1
;using loop
for i=0,n_elements(b)-1 do a[b[i]]+=1
;no loop
result=uniq(b[sort(b)])
result-=[-1,result[0:n_elements(result)-2]]
print,arr
print,result
END
This works but if I was to remove the 3 from the b array, the result is no longer correct.
Any ideas or thoughts?
Thanks, Tim
|
|
|
Re: Incrementing an element multiple times without a loop? [message #88441 is a reply to message #88440] |
Fri, 25 April 2014 08:00   |
Lajos Foldy
Messages: 176 Registered: December 2011
|
Senior Member |
|
|
On Friday, April 25, 2014 4:50:24 PM UTC+2, timbo...@gmail.com wrote:
>
> For example a = [0,0,0], b=[1,1,2], the result should be [0,2,1]
>
> Simply using a[b]+=1 only increments the each unique element in b once and would give [0,1,1]
>
++a[b]
(a[b]+=1 and a[b]++ give different results, I don't know whether this is good or bad :-)
regards,
Lajos
|
|
|
|
|