Home > Enterprise >  how can I add a dot product as a distance function in pdist of matlab
how can I add a dot product as a distance function in pdist of matlab

Time:11-15

mat_vec=zeros(100,10000);

a dot product is dot(xi, xj)

distanceFunction = @(xi, xj)dot(xi, xj)
mat_dist=pdist(mat_vec, distanceFunction)

Error Infomation like

distanceFunction =

  function_handle with value:

    @(xi,xj)dot(xi,xj)

Error using pdist
Error evaluating distance function '@(xi,xj)dot(xi,xj)'.

Error in Task1_lab404_02 (line 45)
mat_dist=pdist(mat_vec, distanceFunction)

Caused by:
    Error using dot
    A and B must be same size.

CodePudding user response:

From pdist documentation (emphasis mine):

A distance function has the form

function D2 = distfun(ZI,ZJ)

where

ZI is a 1-by-n vector containing a single observation.

ZJ is an m2-by-n matrix containing multiple observations. The function must accept a matrix ZJ with an arbitrary number of observations.

You can achieve that if you write the function vectorized over the second input. For dot product this is very easy, using either matrix multiplication:

distanceFunction = @(xi, xj) xj*xi';

or implicit expansion:

distanceFunction = @(xi, xj) sum(conj(xi).*xj, 2);

Note, however, that this is not a true distance function, because for complex inputs distanceFunction(a, b) is not the same as distanceFunction(b, a). Applying pdist will only give one of those results for each pair.

  • Related