MATLAB: How to extract elements of a multi-dimensional array using the rows of another array as the indices? (more detail in the question)

extracting matrix elementsmatrix indexingvectorization

Suppose I have an array
A = [1,2,3;4,5,6;7,8,9]
I have another array, say,
B = [1,3;2,1;3,2]
I would like to have an output of
C = [A(1,3);A(2,1);A(3,2)]
or in other words
C = [A(B(1,1),B(1,2));A(B(2,1),B(2,2));A(B(3,1),B(3,2))]
which is supposed to be
C = [3;4;8]
I was hoping to do this without resorting to a loop such as
for i = 1:3
C(i) = A(B(i,1),B(i,2))
end
I mistakenly tried
C = A(B(:,1),B(:,2))
but clearly that won't work.
Loops will be too time-consuming for me at this point so I was looking for a way to do it at once.
Any help will be appreciated.
Thanks!

Best Answer

A = [1,2,3;4,5,6;7,8,9]
B = [1,3;2,1;3,2]
C = A(sub2ind(size(A),B(:,1),B(:,2))