首页 文章

如何使用列主要顺序将矢量中的值插入矩阵?

提问于
浏览
7

我想将一组表示为矢量的n值插入矩阵中的相应位置集 . 真实世界的应用涉及将一组n个海面温度值插入到一个区域的图像中,该区域表示为尺寸为nrow x ncol> n in的网格,我已经确定了应该接收温度值的n个水像素 . 我遇到的问题是温度值的排序就好像它们来自列主矩阵而不是用于索引R网格的行主要排序 .

这是我的意思的玩具示例 .

> grid <- matrix(0,4,4)
> grid                       # define the base grid
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    0    0    0    0
[3,]    0    0    0    0
[4,]    0    0    0    0

> temps <- c(9,9,9,9,9)     # we have 5 temperature values
> locs <- c(2,3,4,6,7)      # locations in the base grid that are water

> grid[locs] <- temps       # not really what I want - substitution in row-major order
> grid
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    9    9    0    0
[3,]    9    9    0    0
[4,]    9    0    0    0

期望的结果是:

[,1] [,2] [,3] [,4]
[1,]    0    9    9    9
[2,]    0    9    9    0
[3,]    0    0    0    0
[4,]    0    0    0    0

我想我可以使用转置网格,进行替换然后将其转置回来,但我认为有更好的方法来解决这个问题 .

4 回答

  • 3

    这里有几个选项,每个选项都适用于任意维度的矩阵:


    arrayIndByRow <- function(ind, dim) {
       arrayInd(ind, rev(dim))[,2:1]
    }
    
    grid[arrayIndByRow(locs, dim(grid))] <- temps
    grid
    #      [,1] [,2] [,3] [,4]
    # [1,]    0    9    9    9
    # [2,]    0    9    9    0
    # [3,]    0    0    0    0
    # [4,]    0    0    0    0
    

    f <- function(ind, dim) {
        nr <- dim[1]
        nc <- dim[2]
        ii <- ind - 1
        ((ii %/% nc) + 1) + nr*(ii %% nc)
    }
    
    grid[f(locs, dim(grid))] <- 1:5
    grid
    #      [,1] [,2] [,3] [,4]
    # [1,]    0    1    2    3
    # [2,]    0    4    5    0
    # [3,]    0    0    0    0
    # [4,]    0    0    0    0
    
  • 3

    如果你有一个方阵,你可以编写一个小模数函数,用正确的数字替换你的数字:

    new_num <- function(x,num_rows){
      x = x - 1
      row    <- x %/% num_rows
      column <- x %% num_rows
      newnum <- column * num_rows + row + 1
      return(newnum)
    }
    
    temps <- c(9,9,9,9,9)     
    locs <- c(2,3,4,6,7)
    
    new_locs <- new_num(locs,4)
    
    M <- matrix(0,4,4)
    M[new_locs] <- temps
    

    你也可以用非方形矩阵来做这件事,这有点困难 .

  • 3

    你可以用指数做一些工作 . 首先,我们根据列数生成矩阵长度的序列 . 然后我们迭代地将1添加到序列中 . 我们这样做是为了行数 . 然后对位置矢量的该矢量进行子集化将给出矩阵中的位置 .

    x <- seq(1, length(grid), ncol(grid))
    grid[sapply(0:(nrow(grid)-1), "+", x)[locs]] <- temps
    grid
    
    #      [,1] [,2] [,3] [,4]
    # [1,]    0    9    9    9
    # [2,]    0    9    9    0
    # [3,]    0    0    0    0
    # [4,]    0    0    0    0
    
  • 6

    一种方法是使用所需数据创建一个新矩阵,在创建时指定 byrow=TRUE . 为此,您必须创建一个中间向量来存储和修改 grid 的数据:

    grid <- matrix(rep(0,16),ncol=4)
    ##
    temps <- c(9,9,9,9,9)     
    locs <- c(2,3,4,6,7)      
    ##
    #vgrid <- as.numeric(grid)
    vgrid <- c(grid)
    vgrid[locs] <- temps
    ##
    > matrix(vgrid,ncol=ncol(grid),byrow=TRUE)
         [,1] [,2] [,3] [,4]
    [1,]    0    9    9    9
    [2,]    0    9    9    0
    [3,]    0    0    0    0
    [4,]    0    0    0    0
    

相关问题