[R] Trace of product of matrices

peter dalgaard pdalgd at gmail.com
Sun Oct 19 17:42:33 CEST 2014


> On 19 Oct 2014, at 16:43 , Wagner Bonat <wbonat at gmail.com> wrote:
> 
> Dear,
> 
> I have to compute the trace of a product between four matrices. For
> example, I know the matrices Wi, Wj and C, I need to compute this
> 
> -trace(Wi%*%C^-1%*%Wj%*%C^-1)
> 
> 
> I would like to avoid compute the complete matrix and after take the
> diagonal, something like
> 
> sum(diag( solve(Wi,C)%*% solve(Wj,C)))

<this can't be right: it is C that is the invertible matrix>

> 
> Any idea is welcome.
> 

The usual "trick" is that the trace of a matrix product is the inner product in matrix space, which is just the sum of the  elementwise products 

tr(AB) = tr(BA) = sum_i sum_j a_ij b_ij. 

In R, this becomes simply sum(A*B) -- notice that the ordinary product is used, not %*%. So presumably, you are looking for

sum(solve(C, Wi) * solve(C, Wj))


> Thanks
> 
> -- 
> Wagner Hugo Bonat
> LEG - Laboratório de Estatística e Geoinformação
> UFPR - Universidade Federal do Paraná
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list