# [R] need help in understanding R code, and maybe some math

Peter Ehlers ehlers at ucalgary.ca
Sun May 23 12:09:05 CEST 2010

```On 2010-05-23 0:56, john smith wrote:
> Hi,
> I am trying to implement Higham's algorithm for correcting a non positive
> definite covariance matrix.
> I found this code in R:
> http://projects.cs.kent.ac.uk/projects/cxxr/trac/browser/trunk/src/library/Recommended/Matrix/R/nearPD.R?rev=637
>
> I managed to understand most of it, the only line I really don't understand
> is this one:
> X<- tcrossprod(Q * rep(d[p], each=nrow(Q)), Q)
>
> This line is supposed to calculate the matrix product Q*D*Q^T, Q is an n by
> m matrix and R is a diagonal n by n matrix. What does this mean?
> I also don't understand the meaning of a cross product between matrices, I
> only know it between vectors.

You could have a look at the help page for crossprod which
gives the definitions of crossprod and tcrossprod.

Perhaps this will help:

Q <- matrix(1:12, ncol=3)
v <- rep(1:3, each=nrow(Q)
Q
v
Q * v
(Q * v) %*% t(Q)
tcrossprod(Q * v, Q)

-Peter Ehlers

>
> Thanks,