MATLAB: How to use an array of coordinate pairs to index into 2D array

2darraycoordinateindexinglinearMATLABsub2ind

I have a 2D array, "A":
>> A = reshape([1:25],5,5)
A =
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
and I have coordinate pairs (x,y) stored in array "B":
>> B = [ 1 1; 2 2; 3 3]
B =
1 1
2 2
3 3
How can I use "B" to access "A" such that I get something like:
>> A(B)
ans =
1
3
7

Best Answer

You can use the "sub2ind" function to convert the coordinates into linear index of the array and then access the elements:
>> I = sub2ind(size(A),B(:,1),B(:,2));
>> A(I)
ans =
1
3
7