problem in sorting an array with "sortrows" command

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 18 Dec 2021
Edited: Stephen23 on 18 Dec 2021
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'

Sign in to comment.

Accepted Answer

Dave B
Dave B on 18 Dec 2021
Edited: Dave B on 18 Dec 2021
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

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!