function [K] = kernel(x1, x2, varargin)
% Calculates different kernels: linear, polynomial, Gaussian and sigmoid/tanh.
%
% Input:
%   X -- data (rows)
%   varargin -- kernel parameters
% Output:
%   K -- kernel
% Usage:
%   K = kernel(x1, x2, <type>, <p1>, <p2>, <p3>)
%
% (c) 2008-2016 Zalan Bodo

x1 = x1';
x2 = x2';

dim = size(x1, 1);
p{1} = 'lin';
p{2} = 1/dim; p{3} = 1; p{4} = 2;
for i=1:size(varargin, 2)
    p{i} = varargin{i};
end;

switch lower(p{1})
case 'lin'
    K = x1'*x2;
case 'poly'
    K = p{2}*x1'*x2 + p{3};
    K = K.^p{4};
case 'rbf'
    K = (x1.*x1)'*ones(dim, size(x2, 2)) - 2*x1'*x2 + ...
        ones(size(x1, 2), dim)*(x2.*x2);
    K = exp(-p{2}*K);
case 'tanh'
    K = tanh(p{2}*x1'*x2 + p{3});
end;
