# [R] Flattening and unflattening symmetric matrices

Bert Gunter gunter.berton at gene.com
Sat May 1 01:58:04 CEST 2010

```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: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Peter Ehlers
Sent: Friday, April 30, 2010 4:15 PM
To: Nicholas Andrews
Cc: r-help at r-project.org
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

>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>

--
Peter Ehlers
University of Calgary

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help