Indexing matrices along a given dimension

1 次查看(过去 30 天)
Hi all,
Say I have two matrices A=[3,2,1;6,4,5]; B=['c','b','a';'f','d','e'];
(Note the correspondence between elements of A and B)
Now [sorted,idx]=sort(A,2) gives
sorted = [1,2,3;4,5,6] and idx=[3,2,1;2,3,1];
Is there a fast and simple way (without for loops) to use idx to index into B to get ['a','b','c';'d','e','f']?
(In my actual code the size of A and B are pretty big, so efficiency is really important here. Also A and B could be multidimensional matrices and sorting is performed on any arbitrary dimension.)
Thanks!
Niko

采纳的回答

Joseph Cheng
Joseph Cheng 2015-5-14
Pardon my example it's not the best one but pay attention to what i'm trying to accomplish with the indexoffset
%examples
A=[3,2,1;6,4,5];
B=['c','b','a';'f','d','e'];
%perform calculations column based
[sorted,idx] =sort(A')
%where you need to start thinking out of the box
nB= B'; %transpos B such that order will match single index sequences
[row col]= size(A);
indexoffset = repmat(1:3:3*row,col,1)-1;
newB = nB(idx(:)+indexoffset(:))
sortedB = reshape(newB,3,2)'
as sort(A,2) gives the index position per row or in my case sort(A') gives the index per column. We can use that info to generate another matrix of offsets such that you can then reindex B.
  1 个评论
Walter Roberson
Walter Roberson 2015-5-15
Yes, this method generalizes to any dimension, with care. I wrote the appropriate indexing code several years ago but it would be easier for me to re-create it than to attempt to find it (it was part of a rather large program.)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by