I get a Eigen::Tensor<std::complex, 2>
after some operations on a Tensor with more dimensions. Is there an easy way to create a Eigen::MatrixXcf
from this Tensor-object or do I have to copy the values manually?
I am currently using Eigen version 3.3.4, and there is no easy built-in function to cast between Eigen::Tensor types and the more familiar Matrix or Array types. It would have been handy to have something like the .matrix()
or .array()
methods.
There is also no easy way to add such methods via the plugin mechanism, because the Tensor module doesn't seem to support plugins. If anybody knows how please comment.
In the meantime it is possible to make make fairly efficient workarounds using the Map functions. The following works in C++14, for casting Tensors to and from Matrices
#include <unsupported/Eigen/CXX11/Tensor>
#include <iostream>
template<typename T>
using MatrixType = Eigen::Matrix<T,Eigen::Dynamic, Eigen::Dynamic>;
template<typename Scalar,int rank, typename sizeType>
auto Tensor_to_Matrix(const Eigen::Tensor<Scalar,rank> &tensor,const sizeType rows,const sizeType cols)
{
return Eigen::Map<const MatrixType<Scalar>> (tensor.data(), rows,cols);
}
template<typename Scalar, typename... Dims>
auto Matrix_to_Tensor(const MatrixType<Scalar> &matrix, Dims... dims)
{
constexpr int rank = sizeof... (Dims);
return Eigen::TensorMap<Eigen::Tensor<const Scalar, rank>>(matrix.data(), {dims...});
}
int main () {
Eigen::Tensor<double,4> my_rank4 (2,2,2,2);
my_rank4.setRandom();
Eigen::MatrixXd mymatrix = Tensor_to_Matrix(my_rank4, 4,4);
Eigen::Tensor<double,3> my_rank3 = Matrix_to_Tensor(mymatrix, 2,2,4);
std::cout << my_rank3 << std::endl;
return 0;
}
This works with complex types just as well.
Unfortunately these functions only take tensors, not tensor operations. For instance, this doesn't work:
Eigen::MatrixXd mymatrix = Tensor_to_Matrix(my_rank4.shuffle(Eigen::array<long,4>{1,0,3,2}), 4,4);
来源:https://stackoverflow.com/questions/48795789/eigen-unsupported-tensor-to-eigen-matrix