使用坐标向量获取矩阵的元素 [英] Getting elements of a matrix with vectors of coordinates
问题描述
这是一个非常基本的问题,但是我似乎无法在任何地方解决它或找到答案:假设我有两个坐标向量x,y
和一个矩阵m
.
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
.
我想要一个向量z
,这样对于所有i
,z[i] = m[x[i],y[i]]
.
I would like a vector z
such that z[i] = m[x[i],y[i]]
for all i
.
我尝试了z=m[x,y]
,但是这会导致内存溢出.向量和矩阵都很大,因此循环几乎是不可能的.有任何想法吗 ?
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 ?
推荐答案
使用cbind
.这是一个简单的示例:
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
来自?Extract
:
索引的第三种形式是通过一个数字矩阵,每个维都有一列:索引矩阵的每一行然后选择数组的单个元素,结果是一个向量.索引矩阵中不允许使用负索引.允许使用
NA
和零值:索引矩阵中包含零的行将被忽略,而包含NA
的行将在结果中生成NA
.
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 anNA
produce anNA
in the result.
这篇关于使用坐标向量获取矩阵的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!