Vectorization of this Numpy double loop

后端 未结 1 1127
执笔经年
执笔经年 2020-12-10 15:40

How can I vectorize the following double-loop?

I have one N by A matrix and one N by B matrix, where A and B may differ and N is much smaller than A and B. I want to

相关标签:
1条回答
  • 2020-12-10 16:07

    First vectorise foo(), i.e. modify foo() in a way that it can correctly operate on an array of shape (N, A, B), returning an array of shape (A, B). This step is usually the difficult one. How this is done entirely depends on what foo() does. For the given example, it's very easy to do:

    def foo(arr):
        return np.sum(arr, axis=0)
    

    Now, use broadcasting rules to create a (N, A, B) array containing all the vector differences, and pass it to foo():

    foo(a[:, :, np.newaxis] - b[:, np.newaxis])
    
    0 讨论(0)
提交回复
热议问题