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