Janet2001
Janet2001

Reputation: 55

Numpy statement instead of double for-loop

My following Python code is very slow, is there a possibility to write this part completely with a Numpy statement?

    m = len(self.man_list)
    s = len(self.newnew)

self.zeroMatrix = np.zeros((m,s))

    for k in range(m):
        a1 = self.man_list[k][2]
        b1 = self.man_list[k][0]
        a2 = self.man_list[k][3]
        b2 = self.man_list[k][1]
        for f, part in enumerate(self.extra_list):
            x1 = self.extra_list[f][0]
            y1 = self.extra_list[f][2]
            x2 = self.extra_list[f][1]
            y2 = self.extra_list[f][3]

            first = np.array((x1, y1))
            second = np.array((x2, y2))
            third = np.array((a1, b1))
            forth = np.array((a2, b2))


            dist1 = np.linalg.norm(first - third)
            dist2 = np.linalg.norm(second - forth)
            distance = (dist1 + dist2)

            self.zeroMatrix[k][f] = distance

First of all, I create a Matrix with zeros (self.zeroMatrix).

self.man_list and self.extra_list contain the beginning and ending coordinate points of lines. e.g:

self.man_list = [ [ [1,2], [3,4] ],...]

self.extra_list = [ [ [11,30], [4, 10] ],...]

I get the distance from every line of the first list to every line of the other list, then I register this distance-value in the self.zeroMatrix.

I'm very grateful for your answers!

Upvotes: 1

Views: 60

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

You need to vectorize your calls:

man_list = np.array(self.man_list)
extra_list = np.array(self.extra_list)

Then create the sub matrices you need:

first = extra_list[:, None, ::2]
second = extra_list[:, None, 1::2]
third = man_list[None, :, 2::-2]
fourth = man_list[None, :, 3::-2]

And now, compute the norm on the last axis, axis 2.

dist1 = np.linalg.norm(first - third, axis=2)
dist2 = np.linalg.norm(second - fourth, axis=2)
distance = (dist1 + dist2)

And now, you should have in distance the matrix you want.

Upvotes: 2

Related Questions