fix bug #294: add a diagonal() method to SparseMatrix (const)

This commit is contained in:
Gael Guennebaud 2011-12-04 21:49:21 +01:00
parent 69966e90e1
commit 82f9aa194d
3 changed files with 34 additions and 1 deletions

View File

@ -398,7 +398,7 @@ public:
/** \returns the determinant of the underlying matrix from the current factorization */
Scalar determinant() const
{
Scalar detL = Diagonal<const CholMatrixType>(Base::m_matrix).prod();
Scalar detL = Base::m_matrix.diagonal().prod();
return internal::abs2(detL);
}
};

View File

@ -70,6 +70,28 @@ struct traits<SparseMatrix<_Scalar, _Options, _Index> >
};
};
template<typename _Scalar, int _Options, typename _Index, int DiagIndex>
struct traits<Diagonal<const SparseMatrix<_Scalar, _Options, _Index>, DiagIndex> >
{
typedef SparseMatrix<_Scalar, _Options, _Index> MatrixType;
typedef typename nested<MatrixType>::type MatrixTypeNested;
typedef typename remove_reference<MatrixTypeNested>::type _MatrixTypeNested;
typedef _Scalar Scalar;
typedef Dense StorageKind;
typedef _Index Index;
typedef MatrixXpr XprKind;
enum {
RowsAtCompileTime = Dynamic,
ColsAtCompileTime = 1,
MaxRowsAtCompileTime = Dynamic,
MaxColsAtCompileTime = 1,
Flags = 0,
CoeffReadCost = _MatrixTypeNested::CoeffReadCost*10
};
};
} // end namespace internal
template<typename _Scalar, int _Options, typename _Index>
@ -514,6 +536,9 @@ class SparseMatrix
m_data.resize(size);
}
/** \returns a const expression of the diagonal coefficients */
const Diagonal<const SparseMatrix> diagonal() const { return *this; }
/** Default constructor yielding an empty \c 0 \c x \c 0 matrix */
inline SparseMatrix()
: m_outerSize(-1), m_innerSize(0), m_outerIndex(0), m_innerNonZeros(0)

View File

@ -345,6 +345,14 @@ template<typename SparseMatrixType> void sparse_basic(const SparseMatrixType& re
initSparse<Scalar>(density, refMat2, m2);
VERIFY_IS_APPROX(m2.eval(), refMat2.sparseView().eval());
}
// test diagonal
{
DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows);
SparseMatrixType m2(rows, rows);
initSparse<Scalar>(density, refMat2, m2);
VERIFY_IS_APPROX(m2.diagonal(), refMat2.diagonal().eval());
}
}
void test_sparse_basic()