how to get values of a matrix in MATLAB where the indices are given in a MATRIX form?

3 views (last 30 days)
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!

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 14 Aug 2014
n = size(ASorted);
APart = ASorted(sub2ind(n,Index,ones(size(Index,1),1)*(1:n(2))));
  1 Comment
Valeria
Valeria on 16 Aug 2014
Edited: Valeria on 16 Aug 2014
Great, I see it is another way of linear indexing of matrices. It works correctly.
I have to see what is faster.
Thank you Andrei!

Sign in to comment.

More Answers (1)

Christopher Berry
Christopher Berry on 14 Aug 2014
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 Comments
Christopher Berry
Christopher Berry on 14 Aug 2014
Edited: Christopher Berry on 14 Aug 2014
This method should be as efficient as any in MATLAB for two reasons:
  1. repmat is a built-in function (not M-coded)
  2. 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...

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!