开发者

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

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 linear index you can use on the matrix. For example you can extract values of the matrix with either of these two methods

m[2,3] == 24
m[12] == 24

How do you go from (2,3) => 12 or 12 => (2,3) in R

In Matlab the functions you would use for converting matrix subscripts to linear indices and vice vers开发者_开发技巧a are ind2sub and `sub2ind

Is there an equivalent way in R?


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


For higher dimension arrays, there is the arrayInd function.

> abc <- array(dim=c(10,5,5))
> arrayInd(12,dim(abc))
     dim1 dim2 dim3
[1,]    2    2    1


You mostly don't need those functions in R. In Matlab you need those because you can't do e.g.

A(i, j) = x

where i,j,x are three vectors of row and column indices and x contains the corresponding values. (see also this question)

In R you can simply:

A[ cbind(i, j) ] <- x


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


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


Something like this works for arbitrary dimensions-

ind2sub = function(sz,ind)
{
    ind = as.matrix(ind,ncol=1);
    sz = c(1,sz);
    den = 1;
    sub = c();
    for(i in 2:length(sz)){
        den = den * sz[i-1];
        num = den * sz[i];
        s = floor(((ind-1) %% num)/den) + 1;
        sub = cbind(sub,s);
    }
    return(sub);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜