【问题标题】:Converting between matrix subscripts and linear indices (like ind2sub/sub2ind in matlab)在矩阵下标和线性索引之间转换(如 matlab 中的 ind2sub/sub2ind)
【发布时间】:2011-05-26 00:30:07
【问题描述】:

假设你有一个矩阵

m <- matrix(1:25*2, nrow = 5, ncol=5)

如何从矩阵下标(行索引、列索引)转换为可以在矩阵上使用的线性索引。例如,您可以使用这两种方法中的任何一种来提取矩阵的值

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

R 中如何从 (2,3) => 12 或 12 => (2,3) 开始

在 Matlab 中,用于将矩阵下标转换为线性索引(反之亦然)的函数是 ind2sub 和 `sub2ind

R 中有没有等价的方法?

【问题讨论】:

  • 这样的问题表明您将以复杂的方式做一些简单的事情......

标签: r matlab


【解决方案1】:

迟到的答案,但在名为 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 的回答似乎是最好的

【讨论】:

    【解决方案2】:

    这不是我以前用过的东西,但是根据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 这些是我在 R 中重写的函数类型,只是为了具有相同的简单功能。该备忘单是一个很好的参考。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      您在 R 中大多不需要这些功能。在 Matlab 中您需要这些功能,因为您不能这样做,例如

      A(i, j) = x

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

      在 R 中,您可以简单地:

      A[ cbind(i, j) ]

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

          有 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
          

          【讨论】:

            猜你喜欢
            • 2014-03-09
            • 2020-07-12
            • 1970-01-01
            • 2021-09-11
            • 1970-01-01
            • 1970-01-01
            • 2016-04-16
            • 1970-01-01
            • 2014-06-08
            相关资源
            最近更新 更多