R等效于matlab中的ind2sub / sub2ind

时间:2010-12-15 16:04:25

标签: r matlab

Matlab有两个有用的函数,用于将矩阵下标转换为线性索引,反之亦然。 (ind2sub和sub2ind)

R中有相同的方法吗?

6 个答案:

答案 0 :(得分:17)

这不是我之前使用过的,但根据this handy dandy Matlab to R cheat sheet,您可以尝试这样的事情,其中​​m是矩阵中的行数rc分别是行号和列号,ind是线性索引:

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

答案 1 :(得分:8)

对于更高维度的数组,有arrayInd函数。

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

答案 2 :(得分:4)

有row和col函数以矩阵形式返回这些索引。所以它应该像索引这两个函数的返回一样简单:

 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

答案 3 :(得分:4)

你在R中大多不需要那些功能。在Matlab你需要那些因为你不能这样做。

  

A(i,j)= x

其中i,j,x是行和列索引的三个向量,x包含相应的值。 (另见this question

在R中你可以简单地说:

  

A [cbind(i,j)]&lt; - x

答案 4 :(得分:2)

迟到的回答但是在基础包中有一个名为arrayInd

的ind2sub的实际函数
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)

对于sub2ind,JD Long的答案似乎是最好的

答案 5 :(得分:1)

这样的东西适用于任意尺寸 -

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