problem in sorting an array with "sortrows" command

5 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by