Search code examples
pythonnumpyknn

pairwise subtraction of arrays in python


I have two matrices, A of shape 512*3 and B of shape 1024*3 I want to calculate pairwise subtraction between their rows, so the result would be of shape 512*1024*3

(they are actually arrays of 3D point coordinates : x , y , z and I eventually want to find k nearest points from B to every point in A)

and I can't use for loops. is there any pythonic way to do this? thank u.


Solution

  • From the reference I linked in my previous comment:

    http://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc

    You are trying to do this.

    enter image description here

    Just follow the example, as in:

    import numpy as np
    np.random.seed(123)
    
    a = np.random.uniform(size=(8,3)) # or (512,3)
    b = np.random.uniform(size=(16,3)) # or (1024,3)
    
    diff = a[np.newaxis,:,:]-b[:,np.newaxis,:]
    
    dist = np.sqrt(np.sum(diff**2,axis=-1))