Skip to content
Advertisement

Iterate through an adjacency matrix with a list

So I have a n x n adjacency matrix, N x N NumPy array, where the i-th row and the j-th column is the distance between the i-th and j-th cities.

I also have list, in a specific order in which I have to visit the cities and and add the distances together.

m = matrix
i = matrix_row
j = matrix_column

list = [1, 3, 4, 14, 26, 23...]

The list items are pointing to row/column numbers.

So the 2nd row 4th col is:

distance = m[3][14]
d = 124.9

and I would like to add them as:

m[list[0]][list[1]] + m[list[1]][list[2]] + m[list[2]][list[3]]... and so on

How can I iterate through this?

Advertisement

Answer

You can use zip and sum as follows (or itertools.pairwise instead of zip in python 3.10+):

import numpy as np

m = np.reshape(range(9), (3, 3)) # an example matrix
print(m)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]

lst = [0, 2, 1, 0]
total_dist = sum(m[i][j] for i, j in zip(lst, lst[1:]))
print(total_dist) # 12
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement