2017-05-30 3 views
0

Comment puis-je ajouter une SparseMatrix d'Eigen à un Tenseur d'Eigen?Ajouter une SparseMatrix d'Eigen à un Tenseur d'Eigen

Le code suivant (qui ne compile pas) explique ce que j'essaie de faire.

#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; 
} 

Répondre

0

Évidemment, ceci n'est pas implémenté. Vous devez surcharger operator+= pour ces deux types vous-même. Voir this table pour la signature correcte. Voir également »Iterating over the nonzero coefficients « in the Eigen docs pour savoir comment parcourir efficacement une matrice éparse.

#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; 
}