MATLAB: I need an elegant and fast way to get elements by single index in matrix

indexingMATLAB

I have a vector of indexes I that I need to extract from the matrix A (with the same number of rows as I). To make it clear, here is an example:
A=[1,2,3;4,5,6;7,8,9;0,1,2];
I=[1;2;3;1];
I need to get vector V each, i-th, element of which corresponds to the I(i) element taken from i-th row of A. In above example, for all i=1:4, V(i)=A(i,I(i));
In application I need to use it as a method to get elements of one matrix that correspond to the max elements of another matrix. So, for two matrices with the same size A and B, I need elements from matrix A, that correspond to the max elements in the rows from matrix B:
B=rand(10,20);
A=rand(size(B));
[V,I]=max(B,[],2);
for i=1:length(A(:,1))
V(i)=A(i,I(i));
end;
Basically, I need to replace for-loop with something fast, effective and computationally non-demanding.
Thank you

Best Answer

>> diag(A(1:numel(I),I))
Or
>> A(sub2ind(size(A),(1:numel(I))',I))