fn_trace.hpp

Go to the documentation of this file.
00001 // Copyright (C) 2010 NICTA and the authors listed below
00002 // http://nicta.com.au
00003 // 
00004 // Authors:
00005 // - Conrad Sanderson (conradsand at ieee dot org)
00006 // 
00007 // This file is part of the Armadillo C++ library.
00008 // It is provided without any warranty of fitness
00009 // for any purpose. You can redistribute this file
00010 // and/or modify it under the terms of the GNU
00011 // Lesser General Public License (LGPL) as published
00012 // by the Free Software Foundation, either version 3
00013 // of the License or (at your option) any later version.
00014 // (see http://www.opensource.org/licenses for more info)
00015 
00016 
00017 //! \addtogroup fn_trace
00018 //! @{
00019 
00020 
00021 //! Immediate trace (sum of diagonal elements) of a square dense matrix
00022 template<typename T1>
00023 inline
00024 arma_warn_unused
00025 typename T1::elem_type
00026 trace(const Base<typename T1::elem_type,T1>& X)
00027   {
00028   arma_extra_debug_sigprint();
00029   
00030   typedef typename T1::elem_type eT;
00031   
00032   const Proxy<T1> A(X.get_ref());
00033 
00034   arma_debug_check( (A.n_rows != A.n_cols), "trace(): matrix must be square" );
00035   
00036   eT val = eT(0);
00037   
00038   for(u32 i=0; i<A.n_rows; ++i)
00039     {
00040     val += A.at(i,i);
00041     }
00042   
00043   return val;
00044   }
00045 
00046 
00047 
00048 template<typename T1>
00049 inline
00050 arma_warn_unused
00051 typename T1::elem_type
00052 trace(const Op<T1, op_diagmat>& X)
00053   {
00054   arma_extra_debug_sigprint();
00055   
00056   typedef typename T1::elem_type eT;
00057   
00058   const diagmat_proxy<T1> A(X.m);
00059   
00060   const u32 N = A.n_elem;
00061   
00062   eT val = eT(0);
00063   
00064   for(u32 i=0; i<N; ++i)
00065     {
00066     val += A[i];
00067     }
00068   
00069   return val;
00070   }
00071 
00072 
00073 
00074 //! @}