everyone! Suppose I have a vector of length n(n+1)/2:
a = (a_11, a_12, a_22, ...., a_nn)
Now I'd like to turn it into a symmetric matrix, mean

I could assign the value one by one, but I'm wondering if there is some faster to create this matrix? Thanks so much!!
You could write a function that does this:
IF you had your vector as a11,a12,a13..a1n,a22,a23..a2n, a33,..a3n,..ann
They you could do:
vec2mat <- function(x){
p <- sqrt(1 + 8 * length(x))/ 2 - 0.5
m <- matrix(0, p, p)
m[lower.tri(m, diag = TRUE)] <- x
m[upper.tri(m)] <- (t(m))[upper.tri(m)]
m
}
Now:
vec2mat(1:6)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 5
[3,] 3 5 6
vec2mat(1:10)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 2 5 6 7
[3,] 3 6 8 9
[4,] 4 7 9 10
if you had a11, a12,a22,a31, a32, a33...
vec2mat <- function(x){
p <- sqrt(1 + 8 * length(x))/ 2 - 0.5
m <- matrix(0, p, p)
m[upper.tri(m, diag = TRUE)] <- x
m[lower.tri(m)] <- t(m)[lower.tri(m)]
m
}
vec2mat(1:10)
[,1] [,2] [,3] [,4]
[1,] 1 2 4 7
[2,] 2 3 5 8
[3,] 4 5 6 9
[4,] 7 8 9 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With