Indexing matrices along a given dimension

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

Accepted Answer

Joseph Cheng
Joseph Cheng on 14 May 2015
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 Comment
Walter Roberson
Walter Roberson on 15 May 2015
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.)

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays 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!