Sha*_*aun 6 sorting string matlab
在MATLAB中对字符串进行排序的最佳方法是什么,尊重可能出现在字符串中间的数字?
以下示例说明了我的问题.401是数字上高于6的值.因此,当按升序排序时,Ie401sp2字符串应列在Ie6字符串之后.在此示例中,请注意如何对包含数字的以下字符串进行排序.
--- --- Matlab的(不选我所希望的方式)
Ie4_01
Ie4_128
Ie401sp2
IE5
Ie501sp2
IE6
--- Windows 7的---(我想MATLAB的排序方法)
Ie4_01
Ie4_128
IE5
IE6
Ie401sp2
Ie501sp2
Windows 7尊重出现在字符串中间的数字的相对值.在Matlab中执行此操作的最佳方法是什么?我试图避免在一个小的切线上重新发明轮子.
这是一个有点 hacky 的版本,但它大致可以工作:
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
Run Code Online (Sandbox Code Playgroud)