Reputation: 151
I have a list of vectors and I would like to compute the shortest distance between any pair of vectors in the list.
V = [vector([x,y]) for x in [0..1] for y in [0..1]]
output: [(0, 0), (0, 1), (1, 0), (1, 1)]
I would like to get the distance from each vector to another vector. The format of the output is not important, but it could be something similar to
L=[(1,1,sqrt(2)),(1,sqrt(2),1),(1,sqrt(2),1),(sqrt(2),1,1)]
where L[i] returns a tuple that has the distance from V[i] to V[j] (i != j).
At the end I take the smallest number, in this case 1. The vectors I am working with may not always have integers, but they would be over the real numbers.
I could write a function that computes this, but I feel Sage might have it implemented already and I do not know about it. Eventually, I would like to perform this calculation for vectors of higher dimensions. Is there a way to this in Sage?
Upvotes: 0
Views: 767
Reputation: 1696
Does [(v-w).norm() for v in V for w in V]
give you what you want? Or [[(v-w).norm() for v in V] for w in V]
? The first is one big list, while the second is a nested list, one for each v in V.
The norm
method gives the length of a vector, so this computes the length of each difference v-w
for pairs in your set of vectors.
Edit: to remove 0 from the list(s): [[(v-w).norm() for v in V if v != w] for w in V]
or [[(v-w).norm() for v in V if v-w] for w in V]
in the case of nested lists, or [(v-w).norm() for v in V for w in V if v-w]
or [(v-w).norm() for v in V for w in V if v != w]
in the unnested case.
Upvotes: 1