How to get a set of elements from a matrix given a set of index pairs?
조회 수: 4 (최근 30일)
이전 댓글 표시
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!
댓글 수: 0
채택된 답변
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
댓글 수: 0
추가 답변 (1개)
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?
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!