Indexing matrices along a given dimension

1 回表示 (過去 30 日間)
Niko
Niko 2015 年 5 月 14 日
コメント済み: Walter Roberson 2015 年 5 月 15 日
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 件のコメント
Walter Roberson
Walter Roberson 2015 年 5 月 14 日
Yes, it is possible. I will need to write up the math.

サインインしてコメントする。

採用された回答

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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by