Removing loops in numpy for a simple matrix assignment

Viewed 74

How can I remove loops in this simple matrix assignment in order to increase performance?

nk,ncol,nrow=index.shape
for kk in range(0,nk):
   for ii in range(0,nrow):
       for jj in range(0,ncol):
           idx=index[kk][ii][jj]
           counter[idx][ii][jj]+=1

I come from C++ and I am finding it difficult to adapt to numpy's functions to do some very basic matrix manipulation like this one. I think I have simplified it to a one dimensional loop, but this is still too slow for what I need and it seems to me that there is got to be a more direct way of doing it. Any suggestions? thanks

for kk in range(0,nk):
    xx,yy = np.meshgrid(np.arange(ncol),np.arange(nrow))
    counter[index[kk,:,:].flatten(),yy.flatten(),xx.flatten()]+=1    
1 Answers

If I understand it correctly, you are looking for this:

uniq, counter = np.unique(index, return_counts=True, axis=0)

The uniq should give you unique set of x,ys (x,y will be flattened into a single array) and counter corresponding number of repetitions in the array index

EDIT:

Per OP's comment below:

xx,yy = np.meshgrid(np.arange(ncol),np.arange(nrow))
idx, counts = np.unique(np.vstack((index.flatten(),np.repeat(yy.flatten(),nk),np.repeat(xx.flatten(),nk))), return_counts=True,axis=1)
counter[tuple(idx)] = counts
Related