# [R] generating symmetric matrices

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Mon Jul 30 21:01:00 CEST 2007

```On 28-Jul-07 03: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

Would the fact that A + t(A) is symmetric be useful here?

E.g.

p <- 6
A <- matrix(rnorm(p^2),ncol=p)
A <- (A + t(A))/sqrt(2)
diag(A) <- rep(1,p)
round(A,digits=2)
[,1]  [,2]  [,3]  [,4]  [,5]  [,6]
[1,]  1.00  0.53 -0.20  1.27  0.34  0.83
[2,]  0.53  1.00 -0.99 -0.72  0.68 -1.21
[3,] -0.20 -0.99  1.00 -0.62 -0.36 -0.87
[4,]  1.27 -0.72 -0.62  1.00  2.40  0.33
[5,]  0.34  0.68 -0.36  2.40  1.00  0.20
[6,]  0.83 -1.21 -0.87  0.33  0.20  1.00

(Here, because each off-diagonal element of A is the sum of
2 independent N(0,1)s, divided by sqrt(2), the result is
also N(0,1)).

However, whether this is reallyu seful for you depends on
what you want the elements of A to be!

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 30-Jul-07                                       Time: 20:00:55
------------------------------ XFMail ------------------------------

```