I have two numpy arrays. 'A' of size w,h,2 and 'B' with n,2. In other words, A is a 2-dimensional array of 2D vectors while B is a 1D array of 2D vectors. What i want as a result is an array of size w,h,n. The last dimension is an n-dimensional vector where each of the components is the euclidean distance between the corresponding vector from A (denoted by the first two dimensions w and h) and the nth vector of B.
I know that i can just loop through w, h and n in python manually and calculate the distance for each element, but i like to know if there is a smart way to do that with numpy operations to increase performance.
I found some similar questions but unfortunately all of those use input arrays of the same dimensionality.
Approach #1
You could reshape
A
to2D
, useScipy's cdist
that expects 2D arrays as inputs, get those euclidean distances and finally reshape back to3D
.Thus, an implementation would be -
Approach #2
Since, the axis of reduction is of length
2
only, we can just slice the input arrays to save memory on intermediate arrays, like so -Explanation on
A[...,0,None]
andA[...,1,None]
:With that
None
we are just introducing a new axis at the end of slicedA
. Well, let's take a small example -So, we have :
That is essentially :
When the subtraction is performed, the singleton dims are
broadcasted
corresponding to the dimensions of the other participating arrays -We repeat this for the second index along the last axis. We add these two arrays after squaring and finally a square-root to get the final eucl. distances.