Search code examples
arraysnumpybroadcasting

Array Broadcasting without for loop


I have the code

import numpy as np
import math

pos = np.array([[   1.72,   2.56],
                [   0.24,   5.67],
                [  -1.24,   5.45],
                [  -3.17,  -0.23],
                [   1.17,  -1.23],
                [   1.12,   1.08]])

ref = np.array([1.22, 1.18])

# Insert your solution below
d1 = math.sqrt((pos[0,0]-ref[0])**2 + (pos[0,1]-ref[1])**2)
d2 = math.sqrt((pos[1,0]-ref[0])**2 + (pos[1,1]-ref[1])**2)
d3 = math.sqrt((pos[2,0]-ref[0])**2 + (pos[2,1]-ref[1])**2)
d4 = math.sqrt((pos[3,0]-ref[0])**2 + (pos[3,1]-ref[1])**2)
d5 = math.sqrt((pos[4,0]-ref[0])**2 + (pos[4,1]-ref[1])**2)
d6 = math.sqrt((pos[5,0]-ref[0])**2 + (pos[5,1]-ref[1])**2)

The expected answer is

# [ 1.468,  4.596,  4.928 ,  4.611,  2.410,  0.141 ]

Is it possible to make my solution more efficient and short, preferably without the use of a for-loop. Thank you :D


Solution

  • This does the same as your computations. Python's math module is not needed.

    np.sqrt(((pos - ref)**2).sum(1))
    

    Out:

    [1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862, 0.14142136]