Effacer les filtres
Effacer les filtres

Indexing matrices along a given dimension

1 vue (au cours des 30 derniers jours)
Niko
Niko le 14 Mai 2015
Commenté : Walter Roberson le 15 Mai 2015
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
  1 commentaire
Walter Roberson
Walter Roberson le 14 Mai 2015
Yes, it is possible. I will need to write up the math.

Connectez-vous pour commenter.

Réponse acceptée

Joseph Cheng
Joseph Cheng le 14 Mai 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 commentaire
Walter Roberson
Walter Roberson le 15 Mai 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.)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by