特征向量对数无效使用不完整类型的错误

Error with Eigen vector logarithm invalid use of incomplete type

本文关键字:类型 错误 用不完 向量 无效 特征      更新时间:2023-10-16

我正在尝试使用 Eigen 库计算向量的元素自然对数,这是我的代码:

#include <Eigen/Core>
#include <Eigen/Dense>
void function(VectorXd p, VectorXd q) {
    VectorXd kld = p.cwiseQuotient(q);
    kld = kld.log();
    std::cout << kld << std::endl;
}

但是,当编译时

g++ -I eigen_lib -std=c++11 -march=native test_eigen.cpp -o test_eigen

我得到

test_eigen.cpp:15:23: error: invalid use of incomplete type ‘const class Eigen::MatrixLogarithmReturnValue<Eigen::Matrix<double, -1, 1> >’ kld = kld.log();

我错过了什么?

VectorXd::log()是计算方阵的矩阵对数的MatrixBase<...>::log()。如果你想要逐元素对数,你需要使用数组功能:

kld = kld.array().log();
// or:
kld = log(kld.array());

如果所有操作都是按元素进行的,请考虑使用 ArrayXd 而不是 VectorXd

void function(const Eigen::ArrayXd& p, const Eigen::ArrayXd& q) {
    Eigen::ArrayXd kld = log(p/q);
    std::cout << kld << std::endl;
}

要对特征对象(MatrixVector(进行元素级操作,您需要指定该操作。这是通过向Matrix/Vector对象添加.array()来完成的,如下所示:

kld = kld.array().log();

请参阅本教程。

附言 MatrixLogarithmReturnValue是矩阵函数不支持的模块的一部分。