Converting between matrix subscripts and linear indices (like ind2sub/sub2ind in matlab)

前端 未结 6 1907
遥遥无期
遥遥无期 2021-01-01 20:37

Let\'s say you have a matrix

m <- matrix(1:25*2, nrow = 5, ncol=5)

How do you go from matrix subscripts (row index, column index) to a lin

6条回答
  •  轮回少年
    2021-01-01 20:44

    There are row and col functions that return those indices in matrix form. So it should be as simple as indexing the return from those two functions:

     M<- matrix(1:6, 2)
     row(M)[5]
    #[1] 1
     col(M)[5]
    #[1] 3
     rc.ind <- function(M, ind) c(row(M)[ind], col(M)[ind] )
     rc.ind(M,5)
    [1] 1 3
    

提交回复
热议问题