problem in sorting an array with "sortrows" command

1 visualización (últimos 30 días)
Mahsa Rm
Mahsa Rm el 18 de Dic. de 2021
Editada: Stephen23 el 18 de Dic. de 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 comentario
Stephen23
Stephen23 el 18 de Dic. de 2021
Editada: Stephen23 el 18 de Dic. de 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'

Iniciar sesión para comentar.

Respuesta aceptada

Dave B
Dave B el 18 de Dic. de 2021
Editada: Dave B el 18 de Dic. de 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

Más respuestas (0)

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by