[R] Trace of product of matrices

peter dalgaard pdalgd at gmail.com
Sun Oct 19 21:26:39 CEST 2014


> On 19 Oct 2014, at 19:00 , Spencer Graves <spencer.graves at structuremonitoring.com> wrote:
> 
> 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?

Yep... 

tr(AB) = tr(BA) = sum_i sum_j a_ij b_ji

which is of course sum(A*t(B)) or vice versa. Thanks.

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