Getting elements of a matrix with vectors of coordinates

牧云@^-^@ 提交于 2020-01-01 09:53:06

问题


This is a really basic question, but I can't seem to solve it or find an answer for it anywhere : suppose I have two vectors x,y of coordinates and a matrix m.

I would like a vector z such that z[i] = m[x[i],y[i]]for all i.

I tried z=m[x,y], but that creates a memory overflow. The vector and matrix are quite large so looping is pretty much out of the question. Any ideas ?


回答1:


Use cbind. Here's a simple example:

mat <- matrix(1:25, ncol = 5)
mat
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    6   11   16   21
# [2,]    2    7   12   17   22
# [3,]    3    8   13   18   23
# [4,]    4    9   14   19   24
# [5,]    5   10   15   20   25
x <- 1:5
y <- c(2, 3, 1, 4, 3)
mat[cbind(x, y)]
# [1]  6 12  3 19 15

## Verify with a few values...
mat[1, 2]
# [1] 6
mat[2, 3]
# [1] 12
mat[3, 1]
# [1] 3

From ?Extract:

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector. Negative indices are not allowed in the index matrix. NA and zero values are allowed: rows of an index matrix containing a zero are ignored, whereas rows containing an NA produce an NA in the result.




回答2:


Another way is to use the fact that you can index a matrix as if it were a vector, with elements numbered in column-major form. Using the example from @AnandoMahto:

mat[x+nrow(mat)*(y-1)]
[1]  6 12  3 19 15


来源:https://stackoverflow.com/questions/20617371/getting-elements-of-a-matrix-with-vectors-of-coordinates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!