Indexing into a n-by-m matrix using values from a n-by-1 matrix.
Show older comments
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.
Accepted Answer
More Answers (1)
Jan
on 15 Mar 2012
x = magic(6);
y = [1; 3; 2];
z = x(sub2ind(size(x), 1:length(y), y);
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!