I want to compute the L2 norm between a given value x and each cell of a 2d array arr (which is currently of size 1000 x 100. My current approach:

    for k in range(0, 999):
        for l in range(0, 999):
            distance = np.linalg.norm([x - arr[k][l]], ord= 2)

x and arr[k][l] are both scalars. I actually want to compute the pairwise distance of each array cell to the given value x. In the end I need 1000x1000 distances for 1000x 1000 values. Unfortunately, the approach above is a bottleneck, when it comes to the time it takes to finish. Which is why I am searching for a way to speed this up. I am gratefull for any advice.

A reproducable example (as asked for):

arr = [[1, 2, 4, 4], [5, 6, 7, 8]]
x = 2
for k in range(0, 3):
        for l in range(0, 1):
            distance = np.linalg.norm([x - arr[k][l]], ord= 2)

Please note, that the real arr is much bigger. This is merely a toy example.

Actually, I am not bound to use np.linalg.norm(). I simply want the l2 norm for all of these array cells with the given value x. If you know any function which is more suitable, I would be willing to try it.

1

There are 1 best solutions below

1
On

You can do the followng

  1. Substarct x from the array arr
  2. Then compute the norm
    diff = arr - x
    distance = np.linalg.norm(diff, axis=2, ord=2)