Extract numerics from matrix A with logical matrix B I have a matrix A containing numeric values and a matrix B containing 0/1s:

A &lt;- matrix(1:25, 5, 5)
B &lt;- matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0), 5, 5)

A                             B
1    6   11   16   21         0    0    1    0    0
2    7   12   17   22         0    0    0    0    1
3    8   13   18   23         0    0    0    0    1
4    9   14   19   24         0    0    1    0    0
5   10   15   20   25         0    0    1    0    0


I want to extract the elements of A where B==1 in row order. The desired result is:

11 22 23 14 15


I've come up with two possible ways to do this:

#1
rowSums(A*B)

#2
t(A)[as.logical(t(B))]


It seems like there should be a better (more elegant or faster) way to do this...
While rowSums(A*B) looks pretty nice for me, you can also try

A[which(t(B) == 1, arr.ind = T)[,2:1]]