Fast insertion of SparseMatrix (sparse matrix) elements in Eigen

Fast insertion of SparseMatrix (sparse matrix) elements in Eigen - Chenchen's memo (licc.tech)

Eigen::SparseMatrix<float> m(3, 3);
std::vector<Eigen::Triplet<float> > triple;
for (int i = 0; i < 3; i ) {
    for (int j = 0; j < 3; j ) {
        triple.push_back(Eigen::Triplet<float>(i, j, 0.1));
    }
}
triple.push_back(Eigen::Triplet<float>(1, 1, 0.1));    //相同下标重复插入,则表示相加
m.setFromTriplets(triple.begin(), triple.end());

What this code does is create a 3x3 sparse matrix m and set the value of all its elements to 0.1. The specific implementation is as follows:

  1. A sparse matrix named m is defined, the size is 3x3, and the element type is float.

  1. A std::vector named triple is defined to store the nonzero elements of the matrix m.

  1. Use two for loops to traverse all elements of the matrix m, encapsulate its row, column index and value into an object of Triplet type, and add it to triplet.

  1. Outside the loop, add another Triplet object whose row and column index is (1, 1) and the value is 0.1. Since the position has been assigned a value of 0.1 in the above loop, 0.1 is actually added to the value of the position here.

  1. Call the setFromTriplets method of m to set the elements in triple to the nonzero elements of m. Finally, the value of matrix m is: 0.1 0.1 0.1

0.1 0.2 0.1

0.1 0.1 0.1

Guess you like

Origin blog.csdn.net/m0_67357141/article/details/129731203