Constructing a Symmetric Matrix in R Programming (Example Code)
In this tutorial you’ll learn how to construct a symmetric matrix object in the R programming language.
Example: Create Symmetric Matrix Using upper.tri() & lower.tri() Functions
x <- matrix(letters[1:25], nrow = 5) # Create matrix x[upper.tri(x)] <- t(x)[upper.tri(x)] # Add symmetric values diag(x) <- "x" # Replace diagonal x # Display symmetric matrix # [,1] [,2] [,3] [,4] [,5] # [1,] "x" "b" "c" "d" "e" # [2,] "b" "x" "h" "i" "j" # [3,] "c" "h" "x" "n" "o" # [4,] "d" "i" "n" "x" "t" # [5,] "e" "j" "o" "t" "x" |
x <- matrix(letters[1:25], nrow = 5) # Create matrix x[upper.tri(x)] <- t(x)[upper.tri(x)] # Add symmetric values diag(x) <- "x" # Replace diagonal x # Display symmetric matrix # [,1] [,2] [,3] [,4] [,5] # [1,] "x" "b" "c" "d" "e" # [2,] "b" "x" "h" "i" "j" # [3,] "c" "h" "x" "n" "o" # [4,] "d" "i" "n" "x" "t" # [5,] "e" "j" "o" "t" "x"
Related Articles
Please find some related R programming tutorials on topics such as variables and matrices in the following list.