I have following matrix : a = matrix(rnorm(36), 6) Now I want to replace the lower-triangular elements with it's upper-triangular elements. That is I want to make a symmetric matrix from a. I have tried with lower.tri() and upper.tri() function, but got desired result. Can anyone please tell me how to do that?
Symmetric matrix
5 messages · Megh Dal, Jorge Ivan Velez, Dimitris Rizopoulos +2 more
An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20080921/e18ee96d/attachment.pl>
try the following a <- matrix(rnorm(36), 6) ind <- lower.tri(a) a[ind] <- t(a)[ind] a I hope it helps. Best, Dimitris
Megh Dal wrote:
I have following matrix : a = matrix(rnorm(36), 6) Now I want to replace the lower-triangular elements with it's upper-triangular elements. That is I want to make a symmetric matrix from a. I have tried with lower.tri() and upper.tri() function, but got desired result. Can anyone please tell me how to do that?
______________________________________________ R-help at r-project.org 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.
Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014
Jorge Ivan Velez wrote:
Dear Megh, Try this: a = matrix(rnorm(36), 6) a[upper.tri(a)]<-a[lower.tri(a)] a HTH,
If you look carefully, you'll see that it doesn't work! Dimitris had the better idea.
O__ ---- Peter Dalgaard ?ster Farimagsgade 5, Entr.B c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
"DR" == Dimitris Rizopoulos <d.rizopoulos at erasmusmc.nl>
on Sun, 21 Sep 2008 19:58:44 +0200 writes:
DR> try the following
DR> a <- matrix(rnorm(36), 6)
DR> ind <- lower.tri(a)
DR> a[ind] <- t(a)[ind]
DR> a
Yes, indeed, it needs the t(.) trick.
Note that 'Matrix' package has a function forceSymmetric(.) to
do this for you (faster, using C code):
A <- forceSymmetric(Matrix(rnorm(36), 6))
is all you'd need {if can afford to trash half of the random
numbers generated}
Martin Maechler, ETH Zurich
DR> I hope it helps.
DR> Best,
DR> Dimitris
DR> Megh Dal wrote:
>> I have following matrix :
>>
>> a = matrix(rnorm(36), 6)
>>
>> Now I want to replace the lower-triangular elements with it's upper-triangular elements. That is I want to make a symmetric matrix from a. I have tried with lower.tri() and upper.tri() function, but got desired result. Can anyone please tell me how to do that?