Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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

     [,1] [,2]
[1,]    1   12
[2,]   18   10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading