'Extract values from matrix based on a matrix of row indices and matrix of column indices

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?



Solution 1:[1]

array(mat[cbind(c(row_indices), c(col_indices))], dim(row_indices))

     [,1] [,2]
[1,]    1   12
[2,]   18   10

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 onyambu