Array Broadcasting ohne for-Schleife

Nov 10 2020

Ich habe den 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)

Die erwartete Antwort lautet

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

Ist es möglich, meine Lösung effizienter und kurzer zu gestalten, vorzugsweise ohne die Verwendung einer for-Schleife? Vielen Dank: D.

Antworten

2 MichaelSzczesny Nov 10 2020 at 07:59

Dies entspricht den Berechnungen. Pythons mathModul wird nicht benötigt.

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

Aus:

[1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862, 0.14142136]
4 AndyL. Nov 10 2020 at 08:17

Ihre Gleichung ist tatsächlich der euklidische Abstand zwischen posund ref. Sie können Ihre Gleichung mit weiter vereinfachennp.linalg.norm

dist_arr = np.linalg.norm(pos-ref, axis=1)

Out[14]:
array([1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862,
       0.14142136])