      
      if i==j
        RTi =  bsxfun(@times,s,(-2*exp(-2*X(1:D,i)')-2*exp(-2*X(1:D,j)')));
        diRi = -R\bsxfun(@times,RTi(:,d),iR(d,:));
      else
        RTi = bsxfun(@times,s,-2*exp(-2*X(1:D,i)'));
        RTj = bsxfun(@times,s,-2*exp(-2*X(1:D,j)'));
        diRi = -R\bsxfun(@times,RTi(:,d),iR(d,:));
        diRj = -R\bsxfun(@times,RTj(:,d),iR(d,:));
        QdXj = diRj*s/2; % dQ2/dXj
      end
      
      QdXi = diRi*s/2; % dQ2/dXj
      
      if i==j
        daQi = ii*QdXi + bsxfun(@times,