The diag() function in R

后端 未结 2 435
我寻月下人不归
我寻月下人不归 2021-01-18 18:40

Is there a way to use the diag() function in a Matrix without using the built-in function or iteration?

   M<-matrix(1:9, ncol=3) # make a m         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-18 19:15

    You can use the functions row and col to find the indices where the column number is identical to the row number:

    row(M) == col(M)
    #       [,1]  [,2]  [,3]
    # [1,]  TRUE FALSE FALSE
    # [2,] FALSE  TRUE FALSE
    # [3,] FALSE FALSE  TRUE
    
    M[row(M) == col(M)]
    # [1] 1 5 9
    

提交回复
热议问题