2017-05-30 74 views
2

给定一个实验向量c和整数向量rw,我想创建一个向量z与元素z_i=c_i^rw_i。我试图使用组件明智的功能pow,但我得到一个编译器错误。Eigen:向量或矩阵分量来实现?

#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

Compiler是Visual Studio中2015年,在64位运行Windows 7

回答

2

首先,MatrixBase::pow是计算的方阵的矩阵功率(如果该基体具有一个本征值分解,这是一个功能相同的矩阵,但特征值增加到给定的功率)。

你想要的是一个基于元素的电源,由于MatrixBase中没有cwisePow函数,因此需要切换到Array -domain。此外,没有整数专业化的权力(这可能是有效的,但只能达到一定的阈值 - 检查每个元素的阈值会浪费计算时间),所以你需要投入指数的类型你的矩阵。

要还回答您的奖金-问题:

#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'; 
} 

从本质上讲,这将调用C(i,j) = std::pow(A(i,j), b(i))每个ij。如果所有指数都很小,那么实际上可能会比调用专门的pow(double, int)实现(如gcc的__builtin_powi)的简单嵌套循环更快,但您应该将其与实际数据进行基准比较。

+0

我是依靠“系数明智的数学函数目录”(https://eigen.tuxfamily.org/dox/group__CoeffwiseMathFunctions.html),它说电源功能 a.pow(b); pow(a,二); \t增加一个数字给定功率($ a_i^{b_i} $) a和b可以是数组或标量。 \t使用std :: pow; pow(a [i],b [i]); (加整数类型的内建函数) – Woody20