MATLAB Answers

Importing files in the right order

조회 수: 14(최근 30일)
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:
Any simpel way to make this happen?
Thanks in advance!

  댓글 수: 0

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen Cobeldick
Stephen Cobeldick 26 Oct 2020
편집: Stephen Cobeldick 26 Oct 2020
"Any simpel way to make this happen?"
Method one: The simplest way is to rename the files with sufficient leading zeros, e.g.
% ^^ 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 = S(X);

  댓글 수: 3

Tim Johansson
Tim Johansson 26 Oct 2020
Your solution seems to be tailored for cells, does it work on structures too?
Stephen Cobeldick
Stephen Cobeldick 26 Oct 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({});
Rik 26 Oct 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?

댓글을 달려면 로그인하십시오.

추가 답변(0개)


Community Treasure Hunt

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

Start Hunting!

Translated by