Re: [eigen] Diagonal

[ Thread Index | Date Index | More Archives ]

2010/8/19 Will S <billy.baloop@xxxxxxxxx>
So, I've retrieved the diagonal of a square nxn MatrixXd A with:

Diagonal diag = A.diagonal() ;

however oddly diag is a column vector and I cannot use it in
operations (like R = A - diag).

Can I use a diagonal matrix in regular MatrixXd operations?

First of all, .diagonal() doesn't return a diagonal matrix at all, it only returns the column-vector consisting of all diagonal coefficients.

We do have a DiagonalMatrix class, and a method vector.asDiagonal() turning a vector into a diagonal matrix, however, it is one of those "special matrix classes" that support only a rather small subset of operations. General arithmetic is not supported on them, essentially because it would be slow. So,

     someMatrix - someDiagonalMatrix

won't work with Eigen, because there really is no way that the resulting _expression_ could be fast to evaluate as a dense _expression_. Indeed, if you try to compute the (i,j)-th coefficient of that matrix, you have to do a runtime branching:
    if (i == j)
        return someMatrix(i,i) -  someDiagonalMatrix(i,i);
        return someMatrix(i,j);
Since that couldn't be made efficient, we didn't implement it and restricted DiagonalMatrix to support only the operations that are actually efficient on it (for example, products).

Coming back to your use case, if you need to compute
    R = A - diag;
your best bet is to do:
    R = A;
    R.diagonal() -= diag;


Mail converted by MHonArc 2.6.19+