[R] generating symmetric matrices

John Logsdon j.logsdon at quantex-research.com
Mon Jul 30 16:05:50 CEST 2007


Since a symmetric matrix must be square, the following code does it:

> X<-5
> MAT<-matrix(rnorm(X*X),X,X)
> MAT<-MAT+t(MAT)
> MAT
           [,1]       [,2]       [,3]       [,4]       [,5]
[1,]  0.1084372 -1.7867366 -0.9620313 -1.0925719 -0.5902326
[2,] -1.7867366 -0.0462097 -1.2707656  0.6112664  1.8673785
[3,] -0.9620313 -1.2707656 -0.3248162  1.5458446  0.7641865
[4,] -1.0925719  0.6112664  1.5458446 -0.1621192 -1.1381366
[5,] -0.5902326  1.8673785  0.7641865 -1.1381366 -2.8668220

If you want to rescale it, for example to make a correlation matrix with the 
diagonal=1, just use cor():

> cor(MAT)
            [,1]       [,2]        [,3]       [,4]       [,5]
[1,]  1.00000000 -0.2941807  0.03784626 -0.6431474 -0.5743853
[2,] -0.29418072  1.0000000  0.65284419 -0.3410521 -0.5921743
[3,]  0.03784626  0.6528442  1.00000000 -0.2502129 -0.7101451
[4,] -0.64314741 -0.3410521 -0.25021285  1.0000000  0.7593021
[5,] -0.57438527 -0.5921743 -0.71014507  0.7593021  1.0000000

The essential trick is to add matrix to transpose.

On Saturday 28 July 2007 04:28:25 Gregory Gentlemen wrote:
> Greetings,
>
> I have a seemingly simple task which I have not been able to solve today. I
> want to construct a symmetric matrix of arbtriray size w/o using loops. The
> following I thought would do it:
>
> p <- 6
> Rmat <- diag(p)
> dat.cor <- rnorm(p*(p-1)/2)
> Rmat[outer(1:p, 1:p, "<")] <- Rmat[outer(1:p, 1:p, ">")] <- dat.cor
>
> However, the problem is that the matrix is filled by column and so the
> resulting matrix is not symmetric.
>
> I'd be grateful for any adive and/or solutions.
>
> Gregory
>
>
>
>
> ---------------------------------
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.



-- 
Best wishes

John

John Logsdon                               "Try to make things as simple
Quantex Research Ltd, Manchester UK         as possible but not simpler"
j.logsdon at quantex-research.com              a.einstein at relativity.org
+44(0)161 445 4951/G:+44(0)7717758675       www.quantex-research.com



More information about the R-help mailing list