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

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 |

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:

**Please accept YouTube cookies to play this video.** By accepting you will be accessing content from YouTube, a service provided by an external third party.

If you accept this notice, your choice will be saved and the page will refresh.

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

- Create Random Matrix in R
- Create Empty Matrix in R
- Create Matrix that Only Contains Zeros in R
- Create Matrix of Lists in R
- R Programming Overview

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.

### Statistics Globe Newsletter

## 2 Comments. Leave new

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]

Wow, thank you so much György, I have just fixed this error.

Thanks again,

Joachim