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!