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 Comments

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.
Thanks. I've made some research and it seems that MATLAB oop has a major overhead issue...

Sign in to comment.

Answers (0)

Products

Asked:

Roy
on 14 Oct 2014

Commented:

Roy
on 14 Oct 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!