1

I've implemented a custom distance function for k-medoids algorithm in Matlab, following the directions found in pdist.

Basically it compares two vectors, say A and B (which can also have different lengths) and checks if their elements "co-occur with tolerance": A(i) and B(j) co-occur with tolerance tol if

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

Without going into details, the distance is large if there are few "co-occurrences with tolerance".

Everything works as I expect if I define tol as a constant inside the function, but now I would like to pass it as a parameter whenever I call k-medoids. pdist documentation does not mention this possibility:

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,:).

So, is it possible to pass parameters in some way to a custom distance function in Matlab? If not, which alternatives should I consider?

4

1 回答 1

3

要回答您的一般问题,是的,您可以将自定义参数传递给您的自定义距离函数。你可以用这种方式定义 distfun

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

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

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

pdist(X, distanceFunction)
于 2016-03-04T14:17:49.127 回答