Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Last active July 10, 2024 21:47
Show Gist options
  • Save nilforooshan/47a0490745fdb21c502d1502bd56a856 to your computer and use it in GitHub Desktop.
Save nilforooshan/47a0490745fdb21c502d1502bd56a856 to your computer and use it in GitHub Desktop.
R: Turn a vector to a symmetric matrix (row-wise) - specially useful for APEX

Turn a vector to a symmetric matrix (row-wise)

vec2symmat <- function(x) {
    mat.dim <- (sqrt(1 + 8*length(x)) - 1)/2
    if(mat.dim != round(mat.dim)) stop("The vector length does not match with a square matrix dimension.")
    output <- matrix(0, nrow= mat.dim, ncol=mat.dim)
    rownum <- colnum <- c()
    for(i in 1:mat.dim)
    {
        rownum <- c(rownum, rep(i, i))
        colnum <- c(colnum, 1:i)
    }
    x <- data.frame(row=rownum, col=colnum, val=x)
    output[as.matrix(x[,c("row", "col")])] <- x$val
    output <- output + t(output)
    diag(output) <- diag(output)/2
    return(output)
}
vec2symmat(1:6)
     [,1] [,2] [,3]
[1,]    1    2    4
[2,]    2    3    5
[3,]    4    5    6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment