特征值:向量或矩阵分量的幂?

标签 eigen pow

给定一个实数向量 c 和一个整数向量 rw,我想创建一个包含元素 z_i 的向量 z =c_i^rw_i。我尝试使用组件方式函数 pow 来执行此操作,但出现编译器错误。

#include <Eigen/Core>

typedef Eigen::VectorXd RealVector;
typedef Eigen::VectorXi IntVector; // dynamically-sized vector of integers
RealVector c; c << 2, 3, 4, 5;
IntVector rw; rw << 6, 7, 8, 9;
RealVector z = c.pow(rw);    **compile error**

编译器错误是

error C2664: 'const Eigen::MatrixComplexPowerReturnValue<Derived> Eigen::MatrixBase<Derived>::pow(const std::complex<double> &) const': cannot convert argument 1 from 'IntVector' to 'const double &'
      with
      [
          Derived=Eigen::Matrix<double,-1,1,0,-1,1>
      ]
c:\auc\sedanal\LammSolve.h(117): note: Reason: cannot convert from 'IntVector' to 'const double'
c:\auc\sedanal\LammSolve.h(117): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

这段代码有什么问题?并且,假设它可以被修复,当 c 是实数矩阵而不是向量时,我将如何执行相同的操作来计算 c 的所有元素的 c_ij^b_i

编译器是Visual Studio 2015,运行在64位Windows 7下。

最佳答案

首先,MatrixBase::pow 是一个计算方阵矩阵幂的函数(如果矩阵具有特征值分解,则它是相同的矩阵,但特征值增加了)给定的幂)。

您想要的是逐元素幂,由于MatrixBase中没有cwisePow函数,因此需要切换到Array -领域。此外,幂没有整数特化(这可能很有效,但只能达到某个阈值——并且检查每个元素的阈值会浪费计算时间),因此您需要将指数转换为类型你的矩阵。

同时回答您的奖励问题:

#include <iostream>
#include <Eigen/Core>

int main(int argc, char **argv) {
    Eigen::MatrixXd A; A.setRandom(3,4);
    Eigen::VectorXi b = (Eigen::VectorXd::Random(3)*16).cast<int>();

    Eigen::MatrixXd C = A.array() // go to array domain
        .pow(                 // element-wise power
             b.cast<double>() // cast exponents to double
            .replicate(1, A.cols()).array() // repeat exponents to match size of A
        );

    std::cout << A << '\n' << b << '\n' << C << '\n';
}

本质上,这将为每个 i 调用 C(i,j) = std::pow(A(i,j), b(i))j。如果你所有的指数都很小,你实际上可能比使用 简单的嵌套循环,调用专门的 pow(double, int) 实现(如 gcc 的 __builtin_powi),但您应该使用实际数据对其进行基准测试。

关于特征值:向量或矩阵分量的幂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44268968/

相关文章:

c++ - 特征矩阵的就地元素类型转换

c++ - 将 boost cpp_int 用于 pow() 和 rand() 等函数

java - 如何计算 2 的幂 N 其中 N 是一个非常大的数

c++ - 奇怪的 pow(x, y);行为

c++ - Eigen dense matrix * dense vector multiplication 应该比 GSL 慢 7 倍吗?

采用 DenseBase 的模板函数中的 c++ 特征 block 操作

.net - Hat ^ 运算符与 Math.Pow()

c++ - 为什么Webkit运行时pow()计算错误?

c++ - Eigen::RowVector 迭代器

c++ - 需要帮助解决 Eigen 数组并行构造中的数据争用