Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Have you tired pdist2 with custom distance function?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top