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

前端 未结 6 1906
遥遥无期
遥遥无期 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:51

    This is not something I've used before, but according to this handy dandy Matlab to R cheat sheet, you might try something like this, where m is the number of rows in the matrix, r and c are row and column numbers respectively, and ind the linear index:

    MATLAB:

    [r,c] = ind2sub(size(A), ind)
    

    R:

    r = ((ind-1) %% m) + 1
    c = floor((ind-1) / m) + 1
    

    MATLAB:

    ind = sub2ind(size(A), r, c)
    

    R:

    ind = (c-1)*m + r
    

提交回复
热议问题