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

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

    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);
    }
    

提交回复
热议问题