MATLAB: Matrix indexing without loop

matrix indexing

Hello,
Suppose I have two matrices, A and B:
A = [2 3 1 4;
1 4 1 3];
B = [1 2 3 4;
4 3 2 1];
Now I get the max indices for the matrix A:
[~,ind] = max(A,[],2);
I want to obtain the corresponding values of matrix B with ind:
for ii = 1:2
v(ii) = B(ii,ind(ii));
end
How to get the values of B without a for loop?

Best Answer

v = B(sub2ind(size(B), 1:size(B,1), ind))