如何为每行具有不同列位置的矩阵子集? [英] How to subset a matrix with different column positions for each row?
本文介绍了如何为每行具有不同列位置的矩阵子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为每一行使用不同(但只有一个)列的矩阵子集.那么适当申请可以完成这项工作吗?但是智能子集也可以工作,但是我还没有找到解决方案.计算时间是一个问题-我有一个带有for循环的解决方案,但是将矩阵多次加载到RAM中实在太慢了. 这是一个示例:
I want to subset a matrix using different (but one) column for every row. So propably apply could do the job? But propably also smart subsetting could work, but i havent found a solution. Computation time is an issue - I have a solution with a for loop, but loading the matrix in the RAM several times is just too slow. Here is an example:
给出矩阵M和向量v,
M<-matrix(1:15,nrow=5,ncol=3)
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
v<-c(3,1,1,2,1)
,解决方案应为:
(11,2,3,9,5)
推荐答案
我们可以尝试对行/列进行索引
We can try the row/column indexing
M[cbind(1:nrow(M), v)]
#[1] 11 2 3 9 5
这篇关于如何为每行具有不同列位置的矩阵子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文