在Matlab中定义有效的距离函数 [英] Defining an efficient distance function in matlab

查看:326
本文介绍了在Matlab中定义有效的距离函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在matlab中使用kNN搜索功能,但是我正在计算自己定义的类的两个对象之间的距离,因此我编写了一个新的距离函数.就是这样:

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

区别在于obj.Repr可能是一个矩阵,我想计算每个参数的所有行之间的最小距离.但是,即使obj1.Repr只是一个向量,实质上给出了两个向量之间的正常欧几里得距离,kNN函数也要慢200倍!

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!

我已经检查了距离函数的性能(没有kNN).我测量了计算向量与矩阵行(当它们在对象中时)之间的距离所需的时间,它的工作速度比正常距离函数慢了三倍.

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?

推荐答案

您正在使用 dist() ,对应于欧几里得距离权重函数.但是,您没有权衡数据,即您不认为一个维度比其他维度更重要.因此,您可以直接使用欧几里德距离 pdist() :

You are using dist(), which corresponds to the Euclidean distance weight function. However, you are not weighting your data, i.e. you don't consider that one dimension is more important that others. Thus, you can directly use the Euclidean distance pdist():

 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
        X = [obj1.Repr, obj2(i,:).Repr'];
        M = pdist(X,'euclidean');
        d(i) = min(min(M));
    end
end

顺便说一句,我不知道您的矩阵尺寸,因此您需要处理元素的串联才能正确创建X.

BTW, I don't know your matrix dimensions, so you will need to deal with the concatenation of elements to create X correctly.

这篇关于在Matlab中定义有效的距离函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆