Effacer les filtres
Effacer les filtres

advanced sorting of cell array of strings

13 vues (au cours des 30 derniers jours)
Kilian
Kilian le 28 Juil 2012
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.
  1 commentaire
Azzi Abdelmalek
Azzi Abdelmalek le 28 Juil 2012
where are index 4 ,5 , 7 and 8?

Connectez-vous pour commenter.

Réponses (3)

Oleg Komarov
Oleg Komarov le 28 Juil 2012
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 le 28 Juil 2012
k = regexp(files,'((?<=a_20_)\d*)|((?<=rpm_)\d*)','match');
[ii,ii] = sortrows(str2double(cat(1,k{:})),[-1 2]);
files(ii)
  1 commentaire
Eldhose Poulose
Eldhose Poulose le 6 Mar 2020
Modifié(e) : Eldhose Poulose le 6 Mar 2020
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);

Connectez-vous pour commenter.


Kilian
Kilian le 30 Juil 2012
thanks a lot for all your help. this worked fine.
  1 commentaire
Sean de Wolski
Sean de Wolski le 30 Juil 2012
Please accept the answer which you used to mark this thread closed.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by