给定一个实数向量 c
和一个整数向量 rw
,我想创建一个包含元素 z_i 的向量
。我尝试使用组件方式函数 z
=c_i^rw_ipow
来执行此操作,但出现编译器错误。
#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/