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

前端 未结 6 1910
遥遥无期
遥遥无期 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 21:04

    Late answer but there's an actual function for ind2sub in the base package called arrayInd

    m <- matrix(1:25, nrow = 5, ncol=5)
    # linear indices in R increase row number first, then column
    arrayInd(5, dim(m))
    arrayInd(6, dim(m))
    # so, for any arbitrary row/column
    numCol <- 3
    numRow <- 4
    arrayInd(numRow + ((numCol-1) * nrow(m)), dim(m))
    # find the row/column of the maximum element in m
    arrayInd(which.max(m), dim(m))
    # actually which has an arr.ind parameter for returning array indexes
    which(m==which.max(m), arr.ind = T)
    

    For sub2ind, JD Long's answer seems to be the best

提交回复
热议问题