Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting strings in MATLAB like Windows 7 sorts filenames in explorer (respecting numerals mid-string)

What is the best way to sort strings in MATLAB, respecting numerals that could be present mid-string?

The following example illustrates my problem. 401 is a numerically higher value than 6. Therefore, the Ie401sp2 string should be listed after the Ie6 string when sorting in ascending order. In this example, note how the following strings, which contain numerals, are sorted.

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

---Windows 7--- (The way I want MATLAB to sort)
Ie4_01
Ie4_128
Ie5
Ie6
Ie401sp2
Ie501sp2

Windows 7 respects the relative values of the numerals that appear mid-string. What is the best way to do this in Matlab? I am trying to avoid going off on a minor tangent to reinvent the wheel.

like image 937
Shaun Avatar asked Mar 28 '12 06:03

Shaun


1 Answers

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

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
like image 92
Edric Avatar answered Sep 20 '22 22:09

Edric