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

2 ビュー (過去 30 日間)
euksuk jung
euksuk jung 2018 年 6 月 24 日
編集済み: John D'Errico 2018 年 6 月 24 日
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!

採用された回答

John D'Errico
John D'Errico 2018 年 6 月 24 日
編集済み: John D'Errico 2018 年 6 月 24 日
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

その他の回答 (1 件)

Image Analyst
Image Analyst 2018 年 6 月 24 日
編集済み: Image Analyst 2018 年 6 月 24 日
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?

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by