Sorting strings in MATLAB, such as Windows 7, sorts file names in Explorer (based on medium digits)

What is the best way to sort rows in MATLAB, given the numbers that may be present in the middle row?

The following example illustrates my problem. 401 is a numerically higher value than 6. Therefore, line Ie401sp2 should be given after line Ie6 when sorting in ascending order. In this example, notice how the following lines containing numbers are sorted.

--- Matlab --- (Not sorting the way I want)
Ie4_01
Ie4_128
Ie401sp2
IE5
Ie501sp2
Ie6

--- Windows 7 --- (the way I want to sort MATLAB)
Ie4_01
Ie4_128
IE5
IE6
Ie401sp2
Ie501sp2

Windows 7 respects the relative values ​​of the numbers that appear in the middle line. What is the best way to do this in matlab? I try to avoid the slightest touch in order to reinvent the wheel.

+6
source share
1 answer

This is a bit of a hacker version, but it works roughly:

function x = sortit(x) % get a sortable version of each element of x hacked_x = cellfun( @iSortVersion, x, 'UniformOutput', false ); % sort those, discard the sorted output [~, idx] = sort( hacked_x ); % re-order input by sorted order. x = x(idx); end % convert a string with embedded numbers into a sortable string function hack = iSortVersion( in ) pieces = regexp( in, '(\d+|[^\d]+)', 'match' ); pieces = cellfun( @iZeroPadNumbers, pieces, 'UniformOutput', false ); hack = [ pieces{:} ]; end % if a string containing a number, pad with lots of zeros function nhack = iZeroPadNumbers( in ) val = str2double(in); if isnan(val) nhack = in; else nhack = sprintf( '%030d', val ); end end 
+1
source

Source: https://habr.com/ru/post/911836/


All Articles