Importing files in the right order

10 visualizzazioni (ultimi 30 giorni)
Tim Johansson
Tim Johansson il 26 Ott 2020
Modificato: Stephen23 il 26 Ott 2020
Hello!
Im trying to import a series of files and pair them with some other data that i've got.
The problem is that the order in which the data is being imported is incorrect.
i use the code:
filePattern2 = fullfile(myFolder, 'run_*.hdf5'); % Finds file with run_ and a digit in its name
theFiles2 = dir(filePattern2); %20x1 structure of file names and their location
which makes this order:
i would like the numbers to to be in order so:
Run_1
Run_2
...
Run_20
Any simpel way to make this happen?
Thanks in advance!

Risposta accettata

Stephen23
Stephen23 il 26 Ott 2020
Modificato: Stephen23 il 26 Ott 2020
"Any simpel way to make this happen?"
Method one: The simplest way is to rename the files with sufficient leading zeros, e.g.
Run_01.hdf5
% ^^ always two digits with leading zero if required
Then a simple character sort will arrange your filenames into the required order.
Method two: Download my FEX submission natsortfiles:
It has plenty of examples showing how it works, so you shouldn't have any problems using it. If you want to sort the entire structure returned by dir then you will need to obtain natsortfiles' second output (the sort index), e.g.:
S = dir(fullfile(myFolder,'run_*.hdf5'));
[~,X] = natsortfiles({S.name});
S = S(X);
  3 Commenti
Stephen23
Stephen23 il 26 Ott 2020
Modificato: Stephen23 il 26 Ott 2020
"Your solution seems to be tailored for cells, does it work on structures too?"
By design the input to natsortfiles is a cell array of character vectors, but as my answer clearly shows this does not mean that you cannot use it. Take a look at the code in my answer:
  • The function dir returns S, which is a structure array.
  • The output S is that structure array sorted into the order that you requested.
So my "solution" already works on a structure. You can find a slightly more detailed example in the HTML documentation in the section entitled "Example with DIR and a Structure".
Or, if you do not need the entire structure to be sorted, you can just return the sorted filenames:
C = natsortfiles({S.name});
Rik
Rik il 26 Ott 2020
You can use fieldnames to extract the field names of a struct, although that doesn't really make sense to me, as the whole point of structs is to not depend on the order. The code Stephen posted will sort the struct by file name. Is that what you mean by working on structs?

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su File Operations 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