Eigen::MatrixXd sqExp2d(const Eigen::Matrix<double, 2, -1> &x1, const Eigen::Matrix<double, 2, -1> &x2, const Eigen::Vector2d &lengthScale, bool noisy) { // assert(x1.rows() == x2.rows()) int n1 = x1.cols(), n2 = x2.cols(); // Compute the weighted square distances Eigen::Vector2d w = (lengthScale.array().square().cwiseInverse()).matrix(); Eigen::RowVectorXd xx1 = w.replicate(1, n1).cwiseProduct(x1).cwiseProduct(x1).colwise().sum(); Eigen::RowVectorXd xx2 = w.replicate(1, n2).cwiseProduct(x2).cwiseProduct(x2).colwise().sum(); Eigen::MatrixXd x1x2 = w.replicate(1, n1).cwiseProduct(x1).transpose() * x2; // Compute the covariance matrix Eigen::MatrixXd K = (-0.5 * Eigen::MatrixXd::Zero(n1, n2).cwiseMax( xx1.transpose().replicate(1, n2) + xx2.replicate(n1, 1) - 2 * x1x2)).array().exp(); if (noisy) { K += K.colwise().sum().asDiagonal(); } return K; }