Tutorial_sparse_example.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include <Eigen/Sparse>
  2. #include <vector>
  3. #include <iostream>
  4. typedef Eigen::SparseMatrix<double> SpMat; // declares a column-major sparse matrix type of double
  5. typedef Eigen::Triplet<double> T;
  6. void buildProblem(std::vector<T>& coefficients, Eigen::VectorXd& b, int n);
  7. void saveAsBitmap(const Eigen::VectorXd& x, int n, const char* filename);
  8. int main(int argc, char** argv)
  9. {
  10. if(argc!=2) {
  11. std::cerr << "Error: expected one and only one argument.\n";
  12. return -1;
  13. }
  14. int n = 300; // size of the image
  15. int m = n*n; // number of unknowns (=number of pixels)
  16. // Assembly:
  17. std::vector<T> coefficients; // list of non-zeros coefficients
  18. Eigen::VectorXd b(m); // the right hand side-vector resulting from the constraints
  19. buildProblem(coefficients, b, n);
  20. SpMat A(m,m);
  21. A.setFromTriplets(coefficients.begin(), coefficients.end());
  22. // Solving:
  23. Eigen::SimplicialCholesky<SpMat> chol(A); // performs a Cholesky factorization of A
  24. Eigen::VectorXd x = chol.solve(b); // use the factorization to solve for the given right hand side
  25. // Export the result to a file:
  26. saveAsBitmap(x, n, argv[1]);
  27. return 0;
  28. }