Fastest way to find closest value in a vector
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have a serious issue in matlab. I have 2 vectors v1 and v2 and length(v1) = 1376872, length(v2) = 1350228. Vector v2 contains information about position in the original coordinate system. Vector v1 is coordinates from the wanted coordinate system, transformed to the same type of coordinates as v2.
I need to find the closest match between the coordinate systems for each point. So to say, I want a vector of the same length as v1, each element containing the index of the closest point in v2.
I have solved the problem by using a for loop.
ind = -1*ones(length(v1),1);
for k = 1:length(v1)
diff = v1(k)-v2;
[~,minInd] = min(abs(diff));
if abs(real(diff(minInd)))<2.5 && abs(imag(diff(minInd)))<2.5
ind(k) = minInd;
end
end
This is however a really slow process (will take around 10 hours). This time consumption is unacceptable for the application and thus I need to find a faster solution.
If anyone knows how to solve this please help. Also, if there are better ways of mapping values between coordinate systems (which there probably are) this would also be accepted.
BR Patrik
0 commentaires
Réponse acceptée
John D'Errico
le 6 Déc 2013
Modifié(e) : John D'Errico
le 6 Déc 2013
It is important to know if vector v2 is sorted. If it is, then use histc, which will quickly give you the index of the elements just under each element of v1.
Then you check to see if the element above the ones you just found is closer.
Finally, if the vector v2 is NOT sorted, then it is still simple. Just do s sort on v2, to create a vector v3. Keep the tags from that sort. Now, use the scheme I mentioned above to find the closest point in v3. Use the tags from the sort to back out the original index of those elements. If all you needed is the actual closest value, then there is no need to do this last step.
Note that ALL of the above ops are vectorizable. No explicit loops are necessary to do anything I suggested above.
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!