# 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```

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```

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 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

• GyÃ¶rgy SurjÃ¡n
September 1, 2022 7:41 am

This is wrong. my_mat_sym[1,4] and my_mat_sym[4,1] should be equal, but they aren’t. The same holds for [2,3] and [3,2]