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));
end
% z is now [35, 7, 9, 17, 16, 4]'.
I hope this is clear enough, please let me know if it is not.

2 Comments

y has 3 elements only, therefore the loop cannot run until length(x), but until length(y) only. Then z does not need 100 elements, but "z = zeros(length(y), 1)" is better.
Sorry, that was a very lazy updating of the question from me to attempt to make it clearer. Evidently it did much the latter!

Sign in to comment.

 Accepted 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))

1 Comment

My apologies, I must have been unclear. In your example, I would expect z to be [8, 7, 9], which is what my code fragment gives. I will attempt to update my question to make it clearer.

Sign in to comment.

More Answers (1)

x = magic(6);
y = [1; 3; 2];
z = x(sub2ind(size(x), 1:length(y), y);

Categories

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!