How do I sort filenames base on the numbers right before file name in MATLAB?

12 visualizzazioni (ultimi 30 giorni)
Hi
I have file names containing everything, but before the file format (like .mat), there is always a number indicating trials. how can I sort it only base on the trial number before the file format ''.mat''.
here are some examples of my files: S202T4_19112018_MS_T-_21.mat , S202T4_19112018_MS_stay_1.mat
Thanks.
  3 Commenti
m b
m b il 27 Mag 2019
Modificato: m b il 27 Mag 2019
Yes exactly. those are my trial numbers that need to be sorted.
the strings before those numbers are not the same for each file, that's why I need something depends on the numbers before the file format (here .mat).
Rik
Rik il 27 Mag 2019
You can adapt the extract_numbers function to fit any pattern. You can use fileparts to remove the extension and then strfind to find the final underscore. The general structure of my answer should still stand.

Accedi per commentare.

Risposta accettata

Rik
Rik il 27 Mag 2019
This should to the trick. Note that this will return an error if there is no match.
names={'example_1.mat','example_15.mat','example_2.mat'};
numbers=cellfun(@extract_number,names);
[~,order]=sort(numbers);
names=names(order);
function val=extract_number(str)
tokens=regexp(str,'_(\d*).mat','tokens');
val=str2double(tokens{end}{end});
end

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by