MATLAB - 将参数传递给 pdist 自定义距离函数

MATLAB - passing parameters to pdist custom distance function

我按照 pdist 中的说明,在 Matlab 中为 k-medoids 算法实现了自定义距离函数。

基本上它比较两个向量,比如 AB(它们也可以有不同的长度)并检查它们的元素是否 "co-occur with tolerance":A(i)B(j) 与公差共现 tol if

abs( A(i) - B(j) ) <= tol

不细说了,少了距离就大了"co-occurrences with tolerance"。

如果我将 tol 定义为函数内的常量,一切都会按预期进行,但现在我想在调用 k-medoids 时将其作为参数传递。 pdist 文档没有提到这种可能性:

A distance function specified using @: D = pdist(X,@distfun). A distance function must be of form d2 = distfun(XI,XJ), taking as arguments a 1-by-n vector XI, corresponding to a single row of X, and an m2-by-n matrix XJ, corresponding to multiple rows of X. distfun must accept a matrix XJ with an arbitrary number of rows. distfun must return an m2-by-1 vector of distances d2, whose kth element is the distance between XI and XJ(k,:).

那么,是否可以通过某种方式将参数传递给 Matlab 中的自定义距离函数?如果不是,我应该考虑哪些替代方案?

为了回答您的一般性问题,是的,您可以将自定义参数传递给您的自定义距离函数。你可以这样定义 distfun

a = 1; % Variable you want to pass to your function
distanceFunction = @(xi, xj)yourCustomDistanceFunction(xi, xj, a)

yourCustomDistanceFunction 应该接受默认参数作为前两个输入,然后最后一个输入是您自己的变量(pdist 未传递)。

然后通过以下方式提供给pdist

pdist(X, distanceFunction)