how to index a matrix by using a index matrix that has same size?

I have a m by n data matrix and a m by n index matrix which rearranges the order of the n elements in each row of the data matrix. How can I get an indexed data matrix without using loop? Thanks.

1 件のコメント

Ahmed A. Selman
Ahmed A. Selman 2013 年 3 月 30 日
But matrices already are indexed arrays or vectors... right?

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

 採用された回答

Walter Roberson
Walter Roberson 2013 年 3 月 30 日
編集済み: Walter Roberson 2013 年 3 月 30 日

1 投票

Use sub2ind()

3 件のコメント

Cedric
Cedric 2013 年 3 月 30 日
編集済み: Cedric 2013 年 3 月 30 日
typo: sub2ind
To illustrate Walter's answer, if M is the matrix of data and I the matrix of column indices, you can do
rId = (1:size(M,1)).' * ones(1,size(M,2)) ; % Matrix of row indices.
M_reordered = M(sub2ind(size(M), rId, I)) ;
Walter Roberson
Walter Roberson 2013 年 3 月 30 日
Oops, yes, I was concentrating on not putting an "s" in and so left out the "2" :(
Cedric
Cedric 2013 年 3 月 30 日
I thought that you had forgotten the "s" and I ended up realizing that it was a "2" ;-)

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

その他の回答 (2 件)

Anand
Anand 2013 年 3 月 30 日

0 投票

If A is your original matrix and idx is the matrix of indices, you can use logical indexing: A(idx).
Here's an example:
>> A = rand(3)
A =
0.8147 0.9134 0.2785
0.9058 0.6324 0.5469
0.1270 0.0975 0.9575
>> idx = [9 8 7;6 5 4;3 2 1]
idx =
9 8 7
6 5 4
3 2 1
>> A(idx)
ans =
0.9575 0.5469 0.2785
0.0975 0.6324 0.9134
0.1270 0.9058 0.8147

1 件のコメント

Cedric
Cedric 2013 年 3 月 30 日
編集済み: Cedric 2013 年 3 月 30 日
This is linear indexing actually; the idx matrix that you defined is essentially what we get after calling sub2ind() with a third arg that is a matrix of column indices for each row (different from linear index).

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

Piment
Piment 2013 年 3 月 30 日
編集済み: Piment 2013 年 3 月 30 日

0 投票

to be more specific, it's something like(it's actually 300 by 5500 in my case):
A =
0.9649 0.4854 0.9157
0.1576 0.8003 0.7922
0.9706 0.1419 0.9595
0.9572 0.4218 0.6557
idx =
1 3 2
3 1 2
2 1 3
3 2 1

2 件のコメント

Cedric
Cedric 2013 年 3 月 30 日
Walter's answer and my illustration should work; just replace M with A and I with idx.
Piment
Piment 2013 年 3 月 30 日
thank you both, it really does work.

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

カテゴリ

ヘルプ センター および File Exchange で Matrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by