How to create time matrix effectively

Viewed 65

I have a following question. I have a function get_time that return time between two coordinates. I would like to create a time matrix. Here is my code:


def time_matrix(coordinates):
    times = np.zeros((len(coordinates), len(coordinates)), dtype=float)
    for i in range(len(coordinates)):
        for j in range(len(coordinates)):
            time = get_time(
                coordinates[i][0], coordinates[i][1], coordinates[j][0], coordinates[j][1]
            ) / 60
            times[i][j] = time
         
    return times.tolist()

My function works, but it is very ineffective. times is symmetric, so it would be better to use each time twice. In other words, I don`t want to compute the result row by row. Can you help me how can I modify my function, please?

1 Answers

If you just want to use the evaluated time twice, it could simply be achieved by changing the assignment line and limit the second loop

def time_matrix(coordinates):
times = np.zeros((len(coordinates), len(coordinates)), dtype=float)
for i in range(len(coordinates)):
    for j in range(i,len(coordinates)):
        time = get_time(
            coordinates[i][0], coordinates[i][1], coordinates[j][0], coordinates[j][1]
        ) / 60
        times[i][j] = times[j][i] = time
     
return times.tolist()

This should work, right? But a vectorized get_time() would be better, of course.

Related