NumPy Broadcasting: Calculating sum of squared differences between two arrays

You can use np.einsum after calculating the differences in a broadcasted way, like so – ab = a[:,None,:] – b out = np.einsum(‘ijk,ijk->ij’,ab,ab) Or use scipy’s cdist with its optional metric argument set as ‘sqeuclidean’ to give us the squared euclidean distances as needed for our problem, like so – from scipy.spatial.distance import cdist out … Read more

Vectorized NumPy linspace for multiple start and stop values

Here’s an approach using broadcasting – def create_ranges(start, stop, N, endpoint=True): if endpoint==1: divisor = N-1 else: divisor = N steps = (1.0/divisor) * (stop – start) return steps[:,None]*np.arange(N) + start[:,None] Sample run – In [22]: # Setup start, stop for each row and no. of elems in each row …: start = np.array([1,4,2]) …: … Read more

Numpy – create matrix with rows of vector

Certainly possible with broadcasting after adding with m zeros along the columns, like so – np.zeros((m,1),dtype=vector.dtype) + vector Now, NumPy already has an in-built function np.tile for exactly that same task – np.tile(vector,(m,1)) Sample run – In [496]: vector Out[496]: array([4, 5, 8, 2]) In [497]: m = 5 In [498]: np.zeros((m,1),dtype=vector.dtype) + vector Out[498]: … Read more