get closest vector to a vector argument

41 views
Skip to first unread message

justin hidair

unread,
Mar 21, 2017, 2:20:09 PM3/21/17
to Python Programming for Autodesk Maya
How would you find the closest MVector to another MVector (argument) ? Is there a way to do it exclusively using the API ? the only thing I could see is MVector.isEquivalent()
but that's not what I want , even with the tolerance setting, that's just inaccurate ..
I heard about sciPy and numPy without investigating too much...

Michael Boon

unread,
Mar 21, 2017, 4:28:15 PM3/21/17
to Python Programming for Autodesk Maya
You have a list of MVectors and you want to find which of them is closest to a target MVector? Unless your list of MVectors is sorted, you're going to have to compare them all, one at a time. In Python:
closestDist = float("inf")
for i, vec in enumerate(vectors):
    dist = (vec-targetVector).length()
    if dist < shortestDist:
         closestIndex = i
         shortestDist = dist
If you were doing it in C++ you'd probably roll your own distance-squared function, but in Python I think it's faster to call length (which is done in C++).
If your vectors are normalized, you can use the dot product instead of subtraction and length, and that will be faster.
If you have a lot of vectors to compare to your list, you can optimize by sorting the list into an octree first.

justin hidair

unread,
Mar 21, 2017, 6:35:09 PM3/21/17
to Python Programming for Autodesk Maya
No I want to literally find the closest vector , this is not a matter of length but It's about the vectors components + in my case, all vectors are normalized so length is not even relevant yes,
but dot product is not an option, It's barely legal to me to just dot product things for this sake, I'm more interested in solutions like numPy and sciPy, someone has experience with it ?or had this problem ?

Michael Boon

unread,
Mar 21, 2017, 7:37:26 PM3/21/17
to Python Programming for Autodesk Maya
In general, comparing two vectors means getting the length of their difference. If your vectors are normalized, that will still work, but you can do it faster using a dot product. If you replace the line "dist = (vec-targetVector).length()" with "dot = vec * targetVector" above, the largest dot product is the closest vector.

My experience with Maya's Python API 2.0 is that it's as fast or faster than NumPy for dealing with things like MVectorArray or MPointArray, and it's a lot more convenient.

I guess I'm missing something here though. Why is dot product not an option?
Reply all
Reply to author
Forward
0 new messages