Search code examples
rmatrixuser-defined-functionssymmetric

How to manually determine if a matrix is symmetric?


I tried to test if the matrix is symmetric, but this doesn't work.

> View(new.function)
> View(new.function)
> new.function <- function(a){
+     for(i in 1:nrow(a)){
+         for(j in 1:ncol(a)){
+             if(a==t(a)){
+                 print("true")
+             }else{print("false")}
+         }
+     }
+ }
> a <- matrix(1:3,3,3)
> a
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3
> new.function(a)
[1] "true"
[1] "true"
[1] "true"
[1] "true"
[1] "true"
[1] "true"
[1] "true"
[1] "true"
[1] "true"

Solution

  • There is a function in base (as mentioned in the comments) that can get you what you need.

    isSymmetric.matrix(a)
     # [1] FALSE
    

    However, if you want to write up your own function, then you should know that you don't need loops. You can check if a matrix and it's transpose are the same (all of the entries are equal) simply by using all.

    new.function <- function(a) {all(a==t(a))}
    

    or using all.equal (less efficient).

    new.function <- function(a) {all.equal(b, t(b))==1}
    

    If you insist on using loops, then you have to use the indices within your comparison. Here, I changed the way I am comparing the entries. I assume the matrix is symmetric; if one of the indices and its relevant entry from the transposed matrix (a[i,j] will be compared with t(a)[i,j] or a[j,i]) were unequal, then I exit the loops and return FALSE.

    new.function <- function(a){
                     ans = TRUE
                      for(i in 1:nrow(a)){
                      for(j in 1:ncol(a)){
                          if(a[i,j]!=a[j,i]){
                             ans = FALSE;break}
                          }
                      }
                    return(ans)}
    

    But this is not efficient at all.