advanced sorting of cell array of strings

13 次查看(过去 30 天)
I have the following array that I sorted in descending order (natural sort using sortn.m)
files = [
'a_20_15rpm_05.txt'
'a_20_14rpm_05.txt'
'a_20_12rpm_50.txt'
'a_20_12rpm_10.txt'
'a_20_12rpm_05.txt'
'a_20_5rpm_05.txt'
'a_20_4rpm_50.txt'
'a_20_4rpm_05.txt'
'a_20_2rpm_05.txt']
Here is what I need: the elements with equal rpms (index 3, 4 and 5 as well as 7 and 8) need to be sorted in ascending order. The final array should have the following form
files = [
'a_20_15rpm_05.txt'
'a_20_14rpm_05.txt'
'a_20_12rpm_05.txt'
'a_20_12rpm_10.txt'
'a_20_12rpm_50.txt'
'a_20_5rpm_05.txt'
'a_20_4rpm_05.txt'
'a_20_4rpm_50.txt'
'a_20_2rpm_05.txt']
I'd really appreciate some help on this. Thanks a lot for your answers in advance.

回答(3 个)

Oleg Komarov
Oleg Komarov 2012-7-28
Your sample input:
files = {
'a_20_15rpm_05.txt'
'a_20_14rpm_05.txt'
'a_20_12rpm_50.txt'
'a_20_12rpm_10.txt'
'a_20_12rpm_05.txt'
'a_20_5rpm_05.txt'
'a_20_4rpm_50.txt'
'a_20_4rpm_05.txt'
'a_20_2rpm_05.txt'}
% Match the second and third group of digits (it would be nice to see more elegant ways to do that)
out = regexp(files, '(a_20_|rpm_|.txt)','split');
% Convert numeric strings to numbers and "unpack"
out = cell2mat(cellfun(@(x) str2double(x(:,2:3)),out,'un',0));
% Sort
[trash,idx] = sortrows(out,[-1,2]);
files(idx)

Andrei Bobrov
Andrei Bobrov 2012-7-28
k = regexp(files,'((?<=a_20_)\d*)|((?<=rpm_)\d*)','match');
[ii,ii] = sortrows(str2double(cat(1,k{:})),[-1 2]);
files(ii)
  1 个评论
Eldhose Poulose
Eldhose Poulose 2020-3-6
编辑:Eldhose Poulose 2020-3-6
This Works for me. THANK YOU Andrei.
k= regexp(allNames,'((?<=out_)\d*)|((?<=_TRUE1_))','match'); % d* is for the varying variable, for example, 1 2 3 4 5 ...so on
[~,ii]= sortrows(str2double(cat(1,k{:}))); % [-1 2] is for ascending descending try with and without this
allNames= allNames(ii);

请先登录,再进行评论。


Kilian
Kilian 2012-7-30
thanks a lot for all your help. this worked fine.

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by