From 2d7982cf41c7b8ad67c3dfbe202b8d1a0450c20b Mon Sep 17 00:00:00 2001 From: Davis King Date: Sat, 28 Feb 2009 19:32:57 +0000 Subject: [PATCH] Added a trace() function. --HG-- extra : convert_revision : svn%3Afdd8eb12-d10e-0410-9acb-85c331704f74/trunk%402881 --- dlib/matrix/matrix_la.h | 22 ++++++++++++++++++++++ dlib/matrix/matrix_la_abstract.h | 13 +++++++++++++ 2 files changed, 35 insertions(+) diff --git a/dlib/matrix/matrix_la.h b/dlib/matrix/matrix_la.h index 86efd0658..661253ef5 100644 --- a/dlib/matrix/matrix_la.h +++ b/dlib/matrix/matrix_la.h @@ -1388,6 +1388,28 @@ convergence: w = diagm(W); } +// ---------------------------------------------------------------------------------------- + + template < + typename EXP + > + const typename matrix_exp::type trace ( + const matrix_exp& m + ) + { + COMPILE_TIME_ASSERT(matrix_exp::NR == matrix_exp::NC || + matrix_exp::NR == 0 || + matrix_exp::NC == 0 + ); + DLIB_ASSERT(m.nr() == m.nc(), + "\tconst matrix_exp::type trace(const matrix_exp& m)" + << "\n\tYou can only apply trace() to a square matrix" + << "\n\tm.nr(): " << m.nr() + << "\n\tm.nc(): " << m.nc() + ); + return sum(diag(m)); + } + // ---------------------------------------------------------------------------------------- template < diff --git a/dlib/matrix/matrix_la_abstract.h b/dlib/matrix/matrix_la_abstract.h index 8eeb6a998..a3058beed 100644 --- a/dlib/matrix/matrix_la_abstract.h +++ b/dlib/matrix/matrix_la_abstract.h @@ -153,6 +153,19 @@ namespace dlib - returns the determinant of m !*/ +// ---------------------------------------------------------------------------------------- + + const matrix_exp::type trace ( + const matrix_exp& m + ); + /*! + requires + - m is a square matrix + ensures + - returns the trace of m + (i.e. returns sum(diag(m))) + !*/ + // ---------------------------------------------------------------------------------------- const matrix_exp::matrix_type chol (