How to get index of each points in data?

1 回表示 (過去 30 日間)
ha ha
ha ha 2017 年 11 月 18 日
編集済み: KL 2017 年 11 月 18 日
Let's say:
A= [ 111 111 111 22 %index 1
999 999 999 11 %index 2
555 555 555 44 %index 3
222 222 222 33] %index 4
If I want to reorder the rows in matrix A by sorting the elements of column 4 in ascending order, I will use this code:
sort_cell=arrayfun(@(c) sortrows(A,c),[4],'uniform',0);
% generate a cell by sorting matrix A in ascending of column 4
sort_A=sort_cell{:};
% convert cell "sort_cell_A" to matrix
The result will as follows:
sort_A= [ 999 999 999 11
111 111 111 22
222 222 222 33
555 555 555 44 ]
My question is: How can I get back the index matrix from "sort_A" matrix? I hope the result will be:
index=[2
1
4
3]

採用された回答

KL
KL 2017 年 11 月 18 日
編集済み: KL 2017 年 11 月 18 日
Simply use sortrows,
>> [B,index] = sortrows(A,4)
B =
999 999 999 11
111 111 111 22
222 222 222 33
555 555 555 44
index =
2
1
4
3
and below link has all you need:

その他の回答 (2 件)

Are Mjaavatten
Are Mjaavatten 2017 年 11 月 18 日
>> [~,ix] = sort(A(:,4))
ix =
2
1
4
3
>> sort_A = A(ix,:)
sort_A =
999 999 999 11
111 111 111 22
222 222 222 33
555 555 555 44

Stephen23
Stephen23 2017 年 11 月 18 日
編集済み: Stephen23 2017 年 11 月 18 日
Your code would be much simpler if you called sort on the required column:
>> [~,idx] = sort(A(:,4))
idx =
2
1
4
3
>> B = A(idx,:)
B =
999 999 999 11
111 111 111 22
222 222 222 33
555 555 555 44
To get back the original order, call sort again on the indices:
>> [~,idy] = sort(idx)
idy =
2
1
4
3
>> C = B(idy,:)
C =
111 111 111 22
999 999 999 11
555 555 555 44
222 222 222 33

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by