problem in sorting an array with "sortrows" command

5 ビュー (過去 30 日間)
Mahsa Rm
Mahsa Rm 2021 年 12 月 18 日
編集済み: Stephen23 2021 年 12 月 18 日
I have two arrays, one is time and other is direction. I want to sort the directions by time by using the code below. the direction is sorted well but my time array is ruined. how can I fix this? (because I still need the time array)
code's result is shown in the image.
any help will be appreciated.
timeorder=[3.4,7,1,8,5.1,9];
>> direction=['u','d','L','r','u','r'];
>> sorted = (sortrows([timeorder',direction'], 1))' ;
>> timord = sorted(1,:);
>> drc = sorted(2,:);
  1 件のコメント
Stephen23
Stephen23 2021 年 12 月 18 日
編集済み: Stephen23 2021 年 12 月 18 日
Note that is MATLAB square brackets are a concatenation operator, so this
['u','d','L','r','u','r']
is just a complex way of writing this:
'udLrur'

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

採用された回答

Dave B
Dave B 2021 年 12 月 18 日
編集済み: Dave B 2021 年 12 月 18 日
A good way to sort one array using the order of another is with the second output argument of sort:
timeorder=[3.4,7,1,8,5.1,9];
direction=['u','d','L','r','u','r'];
[sortedtimeorder, sortind] = sort(timeorder)
sortedtimeorder = 1×6
1.0000 3.4000 5.1000 7.0000 8.0000 9.0000
sortind = 1×6
3 1 5 2 4 6
sorteddirection=direction(sortind)
sorteddirection = 'Luudrr'
However if you really wanted to use sortrows, you could always convert the values in timord back to numeric (MATLAB turned them into char for you when you combined the two vectors into a matrix):
timeorder=[3.4,7,1,8,5.1,9];
direction=['u','d','L','r','u','r'];
sorted = (sortrows([timeorder',direction'], 1))' ;
timord = sorted(1,:);
drc = sorted(2,:);
double(timord)
ans = 1×6
1 3 5 7 8 9

その他の回答 (0 件)

カテゴリ

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