Reputation: 43
I am trying to perform a column-wise sum operation on an Eigen tensor. In Matlab, the operations look as follows.
// 2D array
A = [1 2 3; 1 2 3; 1 2 3]
// Making the 2D array a 3D array by adding another array to the third dimension
A(:,:,2) = [1 2 3; 1 2 3; 1 2 3]
A =
// First slice
A(:,:,1) = 1 2 3
1 2 3
1 2 3
// Second slice
A(:,:,2) = 1 2 3
1 2 3
1 2 3
// Sum along dim 1
S = sum(A,1)
S=
// slice 1 summed along the columns
S(:,:,1) =
3 6 9
//slice 2 summed along the columns
S(:,:,2) =
3 6 9
This is what I tried in Eigen
#include <iostream>
#include <Eigen/Dense>
#include <unsupported/Eigen/CXX11/Tensor>
using Eigen::MatrixXd;
using Eigen::Tensor;
using namespace Eigen;
using MccTensor2D = Eigen::Tensor<Eigen::scomplex, 2>;
using MccTensor3D = Eigen::Tensor<Eigen::scomplex, 3>;
int main()
{
MccTensor3D testTensor(2,2,2);
testTensor.setRandom();
auto testTensorOp = testTensor.sum(0); //Error here
}
The error is shown below. Thank you for your help in advance.
/usr/include/unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h: In instantiation of ‘const int Eigen::internal::traitsEigen::TensorReductionOp<Eigen::internal::SumReducer<std::complex<float >, const int, const Eigen::Tensorstd::complex<float, 3>, Eigen::MakePointer> >::NumDimensions’: /usr/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h:36:22: required from ‘const int Eigen::TensorBaseEigen::TensorReductionOp<Eigen::internal::SumReducer<std::complex<float >, const int, const Eigen::Tensorstd::complex<float, 3>, Eigen::MakePointer>, 0>::NumDimensions’ /usr/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h:533:5: required from ‘class Eigen::TensorBaseEigen::TensorReductionOp<Eigen::internal::SumReducer<std::complex<float >, const int, const Eigen::Tensorstd::complex<float, 3>, Eigen::MakePointer>, 0>’ /usr/include/unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h:350:7: required from ‘class Eigen::TensorReductionOpEigen::internal::SumReducer<std::complex<float >, const int, const Eigen::Tensorstd::complex<float, 3>, Eigen::MakePointer>’ egExample.cpp:737:30: required from here /usr/include/unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h:33:61: error: incomplete type ‘Eigen::internal::array_size’ used in nested name specifier 33 | static const int NumDimensions = XprTraits::NumDimensions - array_size::value;
Upvotes: 1
Views: 392
Reputation: 526
The reduction operations such as .sum(...)
take a fixed-size array as argument, with a list of dimensions along which to reduce. See here.
So you only need to replace .sum(0)
with .sum(std::array<int,1>{0})
.
Here is a full example:
#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>
int main(){
auto t = Eigen::Tensor<int, 3>(3,3,2);
t.setValues({{{1,1},{2,2},{3,3}},{{1,1},{2,2},{3,3}},{{1,1},{2,2},{3,3}}});
auto ax = std::array<int,1>{0};
auto ts = t.sum(ax);
std::cout << t << '\n';
std::cout << ts << '\n';
}
Upvotes: 1