How to get a set of elements from a matrix given a set of index pairs?

11 views (last 30 days)
Hello,
For instance, Given:
A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
index_set = [1,1; 2,3; 3,1]
% I'd like to get
output = [A(1,1); A(2,3); A(3,1)];
I've tried:
output = diag(A(index_set(:,1), index_set(:,2)))
but I don't think this is an efficient solution.
Is there an efficient way of doing this? Thank you!

Accepted Answer

John D'Errico
John D'Errico on 24 Jun 2018
Edited: John D'Errico on 24 Jun 2018
If you want efficiency, assuming your real problem is much larger, then you need to learn how to use sub2ind. That means you need to start thinking about how MATLAB stores the elements of an array, so you will learn about using a single index into the elements of a multi-dimensional array.
sub2ind helps you here, and does so efficiently.
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
index_set = [1,1; 2,3; 3,1];
A(sub2ind(size(A),index_set(:,1),index_set(:,2)))
ans =
1
6
7

More Answers (1)

Image Analyst
Image Analyst on 24 Jun 2018
Edited: Image Analyst on 24 Jun 2018
Try this:
for k = 1 : size(index_set, 1);
row = index_set(k, 1);
col = index_set(k, 2);
output(k) = A(row, col);
end
Of course the most efficient way was just
output = [A(1,1); A(2,3); A(3,1)];
which you already had. What was wrong with that?

Community Treasure Hunt

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

Start Hunting!