Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the diagonal elements of a matrix?

Tags:

r

I have written a function to store the diagonal elements of a matrix into a vector. but the output is not as I expected. The code is:

diagonal <- function(x) {
  for (i in nrow(x)) {
    for (j in ncol(x)) {
      if (i == j) {
        a <- x[i, j]
      }
    }
  }
  print(a)
}

I am passing a matrix to the function. What is wrong with the code?

like image 963
Moksh Avatar asked Dec 17 '25 21:12

Moksh


1 Answers

We can use the diag function

diag(m1)
#[1] 1 5 9

Or

m1[col(m1)==row(m1)]
#[1] 1 5 9

If we are using the for loop, we are looping by the sequence of rows and columns i.e 1:nrow(x)/1:ncol(x) and not by nrow(x)/ncol(x).

diagonal <- function(x) {
  a <- numeric(0)
 for( i in 1:nrow(x)){ 
  for(j in 1:ncol(x)){
     if(i == j) { 
       a <-  c(a, x[i,j])
     } 
    }
  }
 a
 }

diagonal(m1)
#[1] 1 5 9

data

m1 <- matrix(1:9, ncol=3)
like image 160
akrun Avatar answered Dec 20 '25 14:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!