Defining an efficient distance function
古いコメントを表示
I'm using kNN search function in matlab, but I'm calculating the distance between two objects of my own defined class, so I've written a new distance function. This is it:
function d = allRepDistance(obj1, obj2)
%calculates the min dist. between repr.
% obj2 is a vector, to fit kNN function requirements
n = size(obj2,1);
d = zeros(n,1);
for i=1:n
M = dist(obj1.Repr, [obj2(i,:).Repr]');
d(i) = min(min(M));
end
end
The difference is that obj.Repr may be a matrix, and I want to calculate the minimal distance between all the rows of each argument. But even if obj1.Repr is just a vector, which gives essentially the normal euclidian distance between two vectors, the kNN function is slower by a factor of 200!
I've checked the performance of just the distance function (no kNN). I measured the time it takes to calculate the distance between a vector and the rows of a matrix (when they are in the object), and it work slower by a factor of 3 then the normal distance function.
Does that make any sense? Is there a solution?
2 件のコメント
Adam
2014 年 10 月 14 日
Have you profiled it?
profile on
your code
profile off
profile viewer
I have found in previous versions (haven't really done any analysis in R2014a or b) that some class-based functionality can be very slow. In particular the overhead of accessing a class property. In your case though I don't really see any obvious excessive access of class properties.
I did spend quite a while removing quite a bit of the class-based aspect from a speed-critical algorithm last year though because of the significant increase in overhead it caused. I ended up just breaking all ideas of encapsulation and pulling properties out of a class to run algorithms on the raw data rather than in class methods.
Roy
2014 年 10 月 14 日
回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Nearest Neighbors についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!