Note the "diag" argument of upper.tri(). Thus: x <- A[upper.tri(A,diag=TRUE)]
Then to recreate A from x: A <- matrix(0, 4, 4) A[upper.tri(A,dia=TRUE)] <- X A <- A+t(A) diag(A) <- diag(A)/2 (I grant that the division may cause slight floating point precision error) Bert Gunter Genentech Nonclinical Statistics -----Original Message----- From: [email protected] [mailto:[email protected]] On Behalf Of Peter Ehlers Sent: Friday, April 30, 2010 4:15 PM To: Nicholas Andrews Cc: [email protected] Subject: Re: [R] Flattening and unflattening symmetric matrices On 2010-04-30 15:26, Nicholas Andrews wrote: > Here's an easy question: I'd like to convert a symmetric matrix to a > vector composed of the upper.tri() part of it plus the diagonal, and > convert it back again. What's the best way to achieve this? I'm > wondering if there are some built in functions to do this easily. I > can encode fine: > > v<- c(diag(A),A[upper.tri(A)]) > > but I don't see an easy way to recover A from v without loops. Any tips? To (re)create a symmetric matrix, use A + t(A): If vd is diag(A) part of v and vu is the rest of v, and let's take A to be 4-by-4, then A <- matrix(0, 4, 4) A[upper.tri(A)] <- vu A <- A + t(A) diag(A) <- vd A -Peter Ehlers > > ______________________________________________ > [email protected] 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. > > -- Peter Ehlers University of Calgary ______________________________________________ [email protected] 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. ______________________________________________ [email protected] 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.

