Given an n-by-m matrix x, and a n-by-1 matrix y, how can I turn this into the n-by-1 matrix z where each row i of z is the value x(i, y(i))? That is, I want to assign each row in z the column of x given by y at the same row.

My current horrible loop code is:

` x = magic(6); y = [1; 3; 2; 4; 6; 1]; z = zeros(length(y), 1); for i = 1 : length(y) z(i) = x(i, y(i)); end % z is now [35, 7, 9, 17, 16, 4]'.`

I hope this is clear enough, please let me know if it is not.

## Best Answer