sortrows command doesn't sort numbers properly

14 visualizaciones (últimos 30 días)
Sebastian Cornejo
Sebastian Cornejo el 23 de Mzo. de 2017
Respondida: Sean de Wolski el 23 de Mzo. de 2017
Hello all,
I've been working on a GUI for someone and it involves sorting an excel table using a column. After using the sortrows command on a column I isolated from the table, I noticed it didn't sort the numbers as I intended. This is the most notable example I could find, where 37 and 376183 were misplaced. Anyone know why the sortrows command does this and how I can fix it to where the two numbers should be in their proper places?
'36032'
'36045'
'36049'
'36146'
'36147'
'36149'
'36413'
'36456'
'36478'
'36558'
'36666'
'36696'
'36704'
'37'
'37056'
'37073'
'37084'
'37268'
'37351'
'37472'
'37581'
'376183'
'37663'
'37701'
'37742'

Respuesta aceptada

Star Strider
Star Strider el 23 de Mzo. de 2017
Before you sort them, convert them from strings to double-precision numerical values with the str2double function. As they are now, it’s sorting as strings.

Más respuestas (2)

Guillaume
Guillaume el 23 de Mzo. de 2017
I see no numbers. What I see are char arrays whose characters happen to be digits. As with any string, matlab sort these alphabetically. The same way that 'aaa' comes before 'ab' in the dictionary, '111' comes before '12'.
If you want sortrows to treat these things as numbers, then convert them to numbers with str2double.

Sean de Wolski
Sean de Wolski el 23 de Mzo. de 2017
sort(double(string(c)))
Where c is your cell array. (String requires 16b or newer)

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