Let's say I have a matrix:
mat <- matrix(1:25,nrow=5,ncol=5)
I would like to extract values from this matrix based on a matrix of row indices and another matrix of column indices, say:
row_indices <- matrix(c(1,3,2,5),nrow=2,ncol=2)
col_indices <- matrix(c(1,4,3,2),nrow=2,ncol=2)
So my output should be:
[,1] [,2]
[1,] 1 12
[2,] 18 10
How would I go about doing this in an efficient manner?
CodePudding user response:
array(mat[cbind(c(row_indices), c(col_indices))], dim(row_indices))
[,1] [,2]
[1,] 1 12
[2,] 18 10