\code
-SparseMatrix m1(rows,cols);
-for (int k=0; k::InnerIterator it(m1,k); it; ++it)
+SparseMatrixType mat(rows,cols);
+for (int k=0; k\
\code
-SparseVector v1(size);
-for (SparseVector::InnerIterator it(v1); it; ++it)
+SparseVector vec(size);
+for (SparseVector::InnerIterator it(vec); it; ++it)
{
- it.value(); // == v1[ it.index() ]
+ it.value(); // == vec[ it.index() ]
it.index();
}
\endcode
@@ -112,7 +139,25 @@ for (SparseVector::InnerIterator it(v1); it; ++it)
\section TutorialSparseFilling Filling a sparse matrix
-Unlike dense matrix, filling a sparse matrix efficiently is a though problem which requires some special care from the user. Indeed, directly filling in a random order a matrix in a compressed storage format would requires a lot of searches and memory copies, and some trade of between the efficiency and the ease of use have to be found. In Eigen we currently provide three ways to set the elements of a sparse matrix:
+A DynamicSparseMatrix object can be set and updated just like any dense matrix using the coeffRef(row,col) method. If the coefficient is not stored yet, then it will be inserted in the matrix. Here is an example:
+\code
+DynamicSparseMatrix aux(1000,1000);
+for (...)
+ for each i
+ for each j interacting with i
+ aux.coeffRef(i,j) += foo(o1,o2);
+SparseMatrix mat(aux); // convert the DynamicSparseMatrix to a SparseMatrix
+\endcode
+
+Sometimes, however, we simply want to set all the coefficients of a matrix before using it through standard matrix operations (addition, product, etc.). In that case it faster to use the low-level startFill()/fill()/fillrand()/endFill() interface. Even though this interface is availabe for both sparse matrix types, their respective restrictions slightly differ from one representation to the other. In all case, a call to startFill() set the matrix to zero, and the fill*() functions will fail if the coefficient already exist.
+
+As a first difference, for SparseMatrix, the fill*() functions can only be called inside a startFill()/endFill() pair, and no other member functions are allowed during the filling process, i.e., until endFill() has been called. On the other hand, a DynamicSparseMatrix is always in a stable state, and the startFill()/endFill() functions are only for compatibility purpose.
+
+Another difference is that the fill*() functions must be called with increasing outer indices for a SparseMatrix, while they can be random for a DynamicSparseMatrix.
+
+Finally, the fill() function assumes the coefficient are inserted in a sorted order per inner vector, while the fillrand() variante allows random insertions (the outer indices must still be sorted for SparseMatrix).
+
+Some examples:
1 - If you can set the coefficients in exactly the same order that the storage order, then the matrix can be filled directly and very efficiently. Here is an example initializing a random, row-major sparse matrix:
\code
| |