0

How can I add an Eigen's SparseMatrix to an Eigen's Tensor?

The following code (which does not compile) explains what I am trying to do.

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

using Eigen::Tensor;
using Eigen::SparseMatrix;

int main()
{
      Tensor<double, 2> tensor(10, 10);

      for(int i=0; i < 10; i++) {
        for(int j=0; j < 10; j++) {
            tensor(i, j) = i * 10 + j;
        }
      }

      SparseMatrix<double> sparse(10, 10);

      auto tensor2 = tensor;
      tensor2 += sparse;
      std::cout << tensor2 << std::endl;
}
4

2 回答 2

0

显然,这没有实现。您必须自己重载operator+=这两种类型。请参阅此表以获取正确的签名。另请参阅Eigen 文档中的»迭代非零系数«,了解如何有效地迭代稀疏矩阵。

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

using Eigen::Tensor;
using Eigen::SparseMatrix;

template < typename T >
Tensor<T,2>& operator+=(Tensor<T,2>& lhs, SparseMatrix<T> const& rhs)
{
  for (int k = 0; k < rhs.outerSize(); ++k)
    for (typename SparseMatrix<T>::InnerIterator it(rhs,k); it; ++it)
      lhs(it.row(), it.col()) = it.value();
  return lhs;
}

int main()
{
      Tensor<double, 2> tensor(10, 10);

      for(int i=0; i < 10; i++) {
        for(int j=0; j < 10; j++) {
            tensor(i, j) = i * 10 + j;
        }
      }

      // We want a sparse matrix that is not only zeros
      Eigen::MatrixXd m = Eigen::MatrixXd::Zero(10,10);
      m(0,0) = 1;
      SparseMatrix<double> sparse(10, 10);
      sparse = m.sparseView();

      auto tensor2 = tensor;

      tensor2 += sparse;
      std::cout << tensor2 << std::endl;
}
于 2017-06-01T00:37:23.887 回答
0

你的意思是在+=方法中:

lhs(it.row(), it.col()) += it.value();

并不是

lhs(it.row(), it.col()) = it.value();

?

于 2018-10-10T17:17:59.727 回答