gpt4 book ai didi

c++ - 在 Eigen 中使用 unaryExpr 进行逐元素运算

转载 作者:行者123 更新时间:2023-11-30 05:34:16 27 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数采用复值 vector 并以 double 计算元素的角度。我的代码如下:

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

class Arg {
public:
double operator()(std::complex<double> a) const
{
return std::arg(a);
}
};

template <typename DerivedA, typename DerivedB>
void ArgumentComputer(const Eigen::MatrixBase<DerivedA> &mat, const Eigen::MatrixBase<DerivedB> &_arg)
{

Eigen::MatrixBase<DerivedB>& arg = const_cast<decltype(arg)>(_arg);

// 1st try:
//arg = mat.unaryExpr(std::ptr_fun(std::arg<double>));

//error: no matching function for call to ‘ptr_fun(<unresolved overloaded function type>)’

// 2nd try:
// arg = mat.unaryExpr(Arg{});

// error: static assertion failed: YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY

// 3rd try:
arg = mat.unaryExpr(Arg{}).template cast<double>();

// error: invalid static_cast from type ‘const std::complex<double>’ to type ‘double’
// return static_cast<NewType>(x);


}

int main()
{

Eigen::MatrixXcd myMat = Eigen::MatrixXcd::Random(3, 3);
Eigen::MatrixXd Arg_myMat(3, 3);

ArgumentComputer(myMat, Arg_myMat);

std::cout << myMat << std::endl;
std::cout << Arg_myMat << std::endl;

return 0;
}

我第一次尝试使用ptr_fun,但我猜在解析类型时有问题。然后我尝试编写一个类作为仿函数。在这种情况下,我收到错误消息说我需要进行转换。当我进行转换时,出现 static_cast 错误。所有这三种情况都在代码中给出,编译器消息也作为注释添加。我的错误是什么,我应该怎么写才正确?

最佳答案

您的问题是您在不知不觉中尝试将复数转换为实数。您会看到 std::arg 的返回类型作为double并假设这就是你所拥有的,但实际上它是一个 std::complex<double>因为 mat输入(MatrixXcd)。您的代码可能如下所示:

// 1st try:
//arg = mat.unaryExpr(std::ptr_fun(std::arg<double>)).real(); // Should work but doesn't resolve the template for some reason

// 2nd try:
arg = mat.unaryExpr(Arg{}).real(); // works

我不是 100% 确定为什么您的第一次尝试不起作用。您还可以使用函数代替仿函数:

double myArg(std::complex<double> a)
{
return std::arg(a);
}
//...
arg = mat.unaryExpr(std::ptr_fun(myArg)).real();

关于c++ - 在 Eigen 中使用 unaryExpr 进行逐元素运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34336042/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com