[R] Trace of product of matrices

Spencer Graves spencer.graves at structuremonitoring.com
Sun Oct 19 18:45:38 CEST 2014


On 10/19/2014 8:42 AM, peter dalgaard wrote:
>> 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))

missing a transpose?


 > A <- matrix(1:4, 2)
 > sum(diag(A %*% A))
[1] 29
 > sum(A*A)
[1] 30
 > sum(diag(A %*% t(A)))
[1] 30
 >


       See "Trace of a product" in the Wikipedia article on "Trace 
(linear algebra)" 
(https://en.wikipedia.org/wiki/Trace_%28linear_algebra%29#Trace_of_a_product). 



       Spencer

>> 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.



More information about the R-help mailing list