problem in sorting an array with "sortrows" command

5 Ansichten (letzte 30 Tage)
Mahsa Rm
Mahsa Rm am 18 Dez. 2021
Bearbeitet: Stephen23 am 18 Dez. 2021
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 Kommentar
Stephen23
Stephen23 am 18 Dez. 2021
Bearbeitet: Stephen23 am 18 Dez. 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'

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Dave B
Dave B am 18 Dez. 2021
Bearbeitet: Dave B am 18 Dez. 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

Weitere Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by