Create Symmetric Matrix in R (Example)


In this article you’ll learn how to construct a symmetric matrix in the R programming language.

The tutorial consists of this:

Here’s how to do it.


Creation of Example Data

I’ll use the data below as a basis for this R programming tutorial:

my_mat <- matrix(c(1, 2, 3, 4,                              # Create example matrix
                   0, 1, 5, 6,
                   0, 0, 1, 7,
                   0, 0, 0, 1),
                 ncol = 4)
my_mat                                                      # Print example matrix


table 1 matrix create symmetric matrix


Have a look at the previous table. It shows that the example data has four rows and four columns. At this point, the upper and lower parts of the matrix are not symmetric.


Example: Create Symmetric Matrix Using upper.tri() & lower.tri() Functions

The following code shows how to create a symmetric matrix object (i.e. a square matrix that remains unaltered when it is transposed).

For this task, we can apply the upper.tri and lower.tri functions as shown below:

my_mat_sym <- my_mat                                        # Duplicate matrix
my_mat_sym[upper.tri(my_mat_sym)] <- t(my_mat_sym)[upper.tri(my_mat_sym)] # Insert lower to upper matrix
my_mat_sym                                                  # Print new matrix


table 2 matrix create symmetric matrix


The output of the previously shown R code is shown in Table 2 – We have inserted the values of the lower triangular matrix at the upper triangular matrix as well.

Note that we have not changed the diagonal of our input matrix. In case you want to change those values as well, you may have a look here.


Video & Further Resources

Have a look at the following video that I have published on my YouTube channel. I show the R code of this post in the video:



In addition, you could read some other articles on my homepage.


In this article, you have learned how to create a symmetric data matrix that is equal to its transposed form in the R programming language. Let me know in the comments section, in case you have further questions or comments.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.