how to get values of a matrix in MATLAB where the indices are given in a MATRIX form?
조회 수: 4 (최근 30일)
이전 댓글 표시
Hello! I would be extremely thankful if anyone can help me. I have a problem finding some function in MatLab which would solve my task. I use a function "sort" [ASorted, Index] = sort(A,1,'descend'); which sorts the values in matrix A along the first dimension. Is there an inverse function such that I can find out values of A using ASorted and Index? This function would use Index and depending on the dimension along which the indices are considered it would use the values in Index to identify the values in A. in this case using 1st dimension ('row dimension') we can find A.
Example: ASorted=[10 5 11 15; 8 3 9 13; 5 2 6 12; 4 1 0 7; 1 0 -4 -9]
ASorted =
10 5 11 15
8 3 9 13
5 2 6 12
4 1 0 7
1 0 -4 -9
Index = [2 2 1 4; 3 5 3 5]
Index =
2 2 1 4
3 5 3 5
In this case I would like to find only a part of A - all columns but just two rows.
I want to get
APart =
8 3 11 7
5 0 6 -9
I can't imagine there is no way to get values of A corresponding to indices in Index. If there is one function (sort), there should be another inverse, which allows without loops get values back.
I want to avoid loops and make the code fast. Thank you for any type of help!
댓글 수: 0
채택된 답변
Andrei Bobrov
2014년 8월 14일
n = size(ASorted);
APart = ASorted(sub2ind(n,Index,ones(size(Index,1),1)*(1:n(2))));
추가 답변 (1개)
Christopher Berry
2014년 8월 14일
Valeria,
You can access a subset of the rows (but all of the columns) by converting the column indexes returned by sort into their corresponding linear indexes into ASorted. MATLAB is column major, so every element can be indexed using 1 number, starting in the upper left corner with 1 and going down the columns, left to right, until you are at the bottom right element, which is numel(ASorted).
Create a column offset matrix using repmat and add it to Index like this:
Offset = repmat(0:size(ASorted,1):numel(ASorted)-1,[size(Index,1),1]);
APart = ASorted(Index+Offset);
댓글 수: 3
Christopher Berry
2014년 8월 14일
편집: Christopher Berry
2014년 8월 14일
This method should be as efficient as any in MATLAB for two reasons:
- repmat is a built-in function (not M-coded)
- Linear indexing is also actually faster than (row, col) indexing, due to how the data is stored and accessed (one multiplication vs 2 multiplications and and addition), although, you are doing more processing to get to the linear index in this case...
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!