根据行索引矩阵和列索引矩阵从矩阵中提取值

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

假设我有一个矩阵:

mat <- matrix(1:25,nrow=5,ncol=5)

我想根据一个行索引矩阵和另一个列索引矩阵从这个矩阵中提取值,比如:

row_indices <- matrix(c(1,3,2,5),nrow=2,ncol=2)
col_indices <- matrix(c(1,4,3,2),nrow=2,ncol=2)

所以我的输出应该是:

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

我将如何有效地执行此操作?

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

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