MATLAB: Indexing into a n-by-m matrix using values from a n-by-1 matrix.


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));
% 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

  • Okay, I'm not totally clear and your for-loop does not do what your problem describes.
    We have an nxm matrix, x, for simplicity:
    x = magic(3);
    We have an nx1 vector y:
    y = [1;3;2];
    We want the columns of x to be indexed by y in to the rows of z:
    z = x(:,y)';
    This is what I understood from your description. Please clarify what is right or wrong with it.
    More per comments
    x = magic(3);
    y = [1;3;2];
    z = x(sub2ind(size(x),(1:numel(y))',y))