MATLAB: How to Obtain the Indeces of the Minimum Value of Each Row in a Matrix and then Apply These Indeces to a New Matrix of the Same Size

matrix indecesminimum

Say I have the following matrices:
x = [3 4; 1 3; 2 5; 7 4];
y = [1 2; 3 4; 5 6; 7 8];
If I want the minimum values by row in x, I can use
[M I] = min(x,[],2)
to obtain
M = [3; 1; 2; 4]
I = [1; 1; 1; 2]
but I am not sure how to apply I to the y matrix to obtain
y = [1; 3; 5; 8]
I have found that
diag(y(I,:))
works, but it is not efficient and will not work on the matrix that I need to apply this to, which is size(47*10^6,3). I also tried to use the find command, but I was unable to get that to work either.

Best Answer

Use sub2ind to build a linear index and extract with this.
The rows will be (1:size(y,1)) and the columns will be your I
doc sub2ind
Something like this (not tested)
idx = sub2ind(size(y),(1:size(y,1))',I);
ymn = y(idx)