Re: [eigen] Setting diagonal of a sparse matrix

I'm not sure if there is a better way to 'replace' the diagonal, if it does exist partially already. But setting the entire Matrix S to the diagonal of D goes like this:
```  S = D.diagonal().asDiagonal();  // clears all off-diagonals, of course
```
If you know that there are no entries yet (or don't care), you can do the same with += or -= instead. As the documentation says, S.diagonal()=... only works if all diagonal entries already exist.
```

Christoph

On 2016-09-22 15:14, Brad Bell wrote:
```
```How should one efficiently set the diagonal of an Eigen sparse matrix ?

The following program does not compile if I set
USE_SPARSE_DIAGONAL 1

# include <Eigen/SparseCore>
# include <iostream>

# define USE_SPARSE_DIAGONAL 0
int main()
{   using Eigen::Dynamic;
Eigen::Matrix<double, 3, 3> D = Eigen::Matrix<double, 3,
3>::Identity();
Eigen::SparseMatrix<double> S(3, 3);
D.diagonal() = D.diagonal() / 2.0;
# if USE_SPARSE_DIAGONAL
S.diagonal() = D.diagonal();
# else
for(size_t i = 0; i < 3; i++)
S.coeffRef(i, i) = D(i, i);
# endif
std::cout << "S =\n" << S << "\n";
}
~

```
```
--
Dipl. Inf., Dipl. Math. Christoph Hertzberg

Universität Bremen
FB 3 - Mathematik und Informatik
AG Robotik
Robert-Hooke-Straße 1
28359 Bremen, Germany

Zentrale: +49 421 178 45-6611

Robert-Hooke-Straße 5
28359 Bremen, Germany

Tel.:    +49 421 178 45-4021
Empfang: +49 421 178 45-6600
Fax:     +49 421 178 45-4150
E-Mail:  chtz@xxxxxxxxxxxxxxxxxxxxxxxx

Weitere Informationen: http://www.informatik.uni-bremen.de/robotik

```

 Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/