MATLAB: Use index from max() to extract matching values from another array

arrayindexingmax

Suppose I have 2 n x m arrays A and B and I get the maximum element of each column of A with
[~,I] = max(A)
Now I want to use I to extract the elements of B that correspond to the max element of each column of A.
For example (the example itself is of no particular interest)
A = rand(5)
B = A.^2
[~,I] = max(A)
Now I would like to have a one line command that extracts from B a row vector consisting of, for each j, the I'th element of column j.
Thanks!

Best Answer

Bmax = B(sub2ind(size(B), I, 1:size(B,2)))