Sort one set of data to correspond to another.

2 ビュー (過去 30 日間)
Ronan
Ronan 2015 年 11 月 16 日
編集済み: Stephen23 2015 年 11 月 17 日
Say I have an ordered set of data.
a = [100,200,300,400,500];
And say I have another set of data,
b = [300,200,500,400,100]
I m trying to find the index where a is sorted to b. I could use a nested for loop of course but is there a better way to get the index shown below?
c = [5,2,1,4,3]

採用された回答

Thorsten
Thorsten 2015 年 11 月 16 日
編集済み: Thorsten 2015 年 11 月 16 日
If b is an unsorted version of a, i.e., all elements in b occur once and only once in a, you can use
[~, idx] = sort(b);
In the more general case where b can have some elements of a, and elements can occur more than once, use
for i=1:numel(b), idx(i) = find(ismember(a, b(i))); end
Instead of the for loop, you can also use
idx = arrayfun(@(x) find(ismember(a,x)), b);
  4 件のコメント
Ronan
Ronan 2015 年 11 月 16 日
Thank you very much.
Guillaume
Guillaume 2015 年 11 月 16 日
編集済み: Guillaume 2015 年 11 月 16 日
z = arrayfun(@(i) find(ismember(k,i)), x)
Is actually not going to work in the general case, because find may return none or several indices, which would then require a 'UniformOutput', false to arrayfun.
If you assume that find is always going to return one and only one value. Then the second output of ismember is a much more efficient way (no loop) to obtain the same result.

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

その他の回答 (2 件)

Stephen23
Stephen23 2015 年 11 月 16 日
編集済み: Stephen23 2015 年 11 月 17 日
>> a = [100,200,300,400,500];
>> b = [300,200,500,400,100];
>> [~,Xa] = sort(a);
>> [~,Xb] = sort(b);
>> Xa(Xb)
ans =
5 2 1 4 3

Guillaume
Guillaume 2015 年 11 月 16 日
Following your comment to Thorsten's answer, use the 2nd return value of ismember:
x = [350,420,245,100]
k = [420,100,350,245]
z = ismember(x, k)

カテゴリ

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