1

I'd like to compute kernel matrices efficiently for generic kernel functions in Matlab. This means I need to compute k(x,y) for every row x of X and every row y of Y. Here is some matlab code that computes what I'd like, but it is rather slow,

function K=compute_kernel( k_func, X, Y )
    m = size(X,1);
    n = size(Y,1);
    K = zeros(m,n);
    for i = 1:m
        for j = 1:n
            K(i,j) = k_func(X(i,:)', Y(j,:)');
        end
    end
end

Is there any other approach to this problem, e.g. some bsxfun variant that calls a function on every row taken from X and Y?

Shai
  • 111,146
  • 38
  • 238
  • 371
Arun Chaganty
  • 341
  • 3
  • 13

2 Answers2

1

pdist2(X,Y, dist_func) unfortunately computes dist_func(X, Y(i,:)), instead of dist_func(X(i,:), Y(i,:)). So the actual function I need is,

function K=compute_kernel( k_func, X, Y )
  % Woohoo! Efficient way to compute kernel
  size(X)
  size(Y)
  m = size(X,1);
  n = size(Y,1);
  for i = 1:n
    K(:,i) = pdist2( Y(i,:), X, k_func);
end

It's not as nice as just using pdist2, but is still much more efficient than the previous case.

Shai
  • 111,146
  • 38
  • 238
  • 371
Arun Chaganty
  • 341
  • 3
  • 13
0

Have you tired pdist2 with custom distance function?

P.S.
It is best not to use i and j as variables in Matlab

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371