2017-05-30 22 views
0

如何添加Eigen的SparseMatrix到Eigen的張量?將Eigen的SparseMatrix添加到Eigen的張量

下面的代碼(不能編譯)解釋了我正在嘗試做的事情。

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

回答

0

很明顯,這沒有實現。您必須自行爲這兩種類型重載operator+=。請參閱​​以獲取正確的簽名。關於如何有效地迭代稀疏矩陣,另請參閱»Iterating over the nonzero coefficients « in the Eigen docs

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