我有一个由多个字符串组成的单元格数组
names = {'2name_19surn', '3name_2surn', '1name_2surn', '10name_1surn'}
我想根据prefixnumber对它们进行排序。
我试过
[~,index] = sortrows(names.');
sorted_names = names(index);
但我得到
sorted_names = {'10name_1surn', '1name_2surn', '2name_19surn', '3name_2surn'}
而不是所需的
sorted_names = {'1name_2surn', '2name_19surn', '3name_2surn','10name_1surn'}
任何建议?
答案 0 :(得分:2)
只要速度不是问题,您就可以遍历所有字符串并将第一个digets保存在数组中。随后按常规排序数组......
names = {'2name_2', '3name', '1name', '10name'}
number_in_string = zeros(1,length(names));
% Read numbers from the strings
for ii = 1:length(names)
number_in_string(ii) = sscanf(names{ii}, '%i');
end
% Sort names using number_in_string
[sorted, idx] = sort(number_in_string)
sorted_names = names(idx)
答案 1 :(得分:2)
使用正则表达式的简单方法:
r = regexp(names,'^\d+','match'); %// get prefixes
[~, ind] = sort(cellfun(@(c) str2num(c{1}), r)); %// convert to numbers and sort
sorted_names = names(ind); %// use index to build result
答案 2 :(得分:1)
从here
获取文件sort_nat然后
names = {'2name', '3name', '1name', '10name'}
sort_nat(names)
返回
sorted_names = {'1name', '2name', '3name','10name'}
答案 3 :(得分:1)
您可以使用正则表达式处理任意模式:
names = {'2name', '3name', '1name', '10name'}
match = regexpi(names,'(?<number>\d+)\D+','names'); % created with regex editor on rubular.com
match = cell2mat(match); % cell array to struct array
clear numbersStr
[numbersStr{1:length(match)}] = match.number; % cell array with number strings
numbers = str2double(numbersStr); % vector of numbers
[B,I] = sort(numbers); % sorted vector of numbers (B) and the indices (I)
clear namesSorted
[namesSorted{1:length(names)}] = names{I} % cell array with sorted name strings