Azzera filtri
Azzera filtri

Indexing matrices along a given dimension

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Joseph Cheng
Joseph Cheng il 14 Mag 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 Commento
Walter Roberson
Walter Roberson il 15 Mag 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.)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by