尝试从以 .sum() 结尾的链式 Eigen::Tensor 操作中提取标量时出错

问题描述 投票:0回答:1

我有以下脚本

#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>

int main() {
    using namespace Eigen;
    // fill the tensor with arbitrary data
    Tensor<std::complex<double>, 4> xi1st(3, 3, 3, 3);
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                for (int l = 0; l < 3; ++l) {
                    xi1st(i, j, k, l) = std::complex<double>(i + j + k + l, i - j + k - l);
                }
            }
        }
    }
    // example indices
    int i = 1, j = 1, k = 1;
    // try to extract sum out of nested operation
    auto xi1st_slice = xi1st.slice(Eigen::array<Index, 4>({0, i, j, k}), Eigen::array<Index, 4>({3, 1, 1, 1}));
    auto xi1st_conj = xi1st_slice.conjugate();
    std::complex<double> xi1st_sum = xi1st_conj.sum();
    std::cout << "xi1st_sum: " << xi1st_sum << std::endl;
    return 0;
}

这会产生编译错误

<source>: In function 'int main()':
<source>:31:52: error: conversion from 'const Eigen::TensorReductionOp<Eigen::internal::SumReducer<std::complex<double> >, const Eigen::DimensionList<long int, 4>, const Eigen::TensorCwiseUnaryOp<Eigen::internal::scalar_conjugate_op<std::complex<double> >, const Eigen::TensorSlicingOp<const std::array<long int, 4>, const std::array<long int, 4>, Eigen::Tensor<std::complex<double>, 4> > >, Eigen::MakePointer>' to non-scalar type 'std::complex<double>' requested
   31 |     std::complex<double> xi1st_sum = xi1st_conj.sum();
      |                                      ~~~~~~~~~~~~~~^~
Compiler returned: 1

我找不到从

.sum()
操作中提取标量的方法。理想情况下,我想将所有内容都链接在一个命令中,但即使一步一步地执行似乎也会引起问题,我们在这里缺少什么?

c++ eigen tensor eigen3
1个回答
0
投票

我找到了一种使用另一个中间体的解决方法:

#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>

int main() {
    using namespace Eigen;
    Tensor<std::complex<double>, 4> xi1st(3, 3, 3, 3);
    for (int a = 0; a < 3; ++a) {
        for (int b = 0; b < 3; ++b) {
            for (int c = 0; c < 3; ++c) {
                for (int d = 0; d < 3; ++d) {
                    xi1st(a, b, c, d) = std::complex<double>(a + b + c + d, a - b + c - d);
                }
            }
        }
    }
    int i = 1, j = 1, k = 1;
    Eigen::array<Index, 4> offsets = {0, i, j, k};
    Eigen::array<Index, 4> extents = {3, 1, 1, 1};
    auto xi1st_slice = xi1st.slice(offsets, extents);
    auto xi1st_conj = xi1st_slice.conjugate();
    Tensor<std::complex<double>, 0> xi1st_sum_tensor = xi1st_conj.sum();
    std::complex<double> xi1st_sum = xi1st_sum_tensor(0);
    std::cout << "xi1st_sum: " << xi1st_sum << std::endl;
    return 0;
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.