MATLAB: Is it possible to extract the values with a vector of indices for each row without using the for statement from the matrix

indexing

Consider the following example.
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]; % reference matrix
b = [2; 1; 1; 3]; % index for each row that I want to extract
for i=1:size(A,1)
y(i,1) = A(i,b);
end
I am using the above code to extract values that I want.
Is there any simple function to implement the above script fast?

Best Answer

see sub2ind()
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]; % reference matrix
b = [2; 1; 1; 3]; % index for each row that I want to extract
idx = sub2ind(size(A), 1:size(A,1), b.');
A(idx)
Result
>> A(idx)
ans =
2 4 7 12