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

2 vues (au cours des 30 derniers jours)
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!

Réponse acceptée

John D'Errico
John D'Errico le 24 Juin 2018
Modifié(e) : John D'Errico le 24 Juin 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

Plus de réponses (1)

Image Analyst
Image Analyst le 24 Juin 2018
Modifié(e) : Image Analyst le 24 Juin 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?

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by