Importing files in the right order

조회 수: 10 (최근 30일)
Tim Johansson
Tim Johansson 2020년 10월 26일
편집: Stephen23 2020년 10월 26일
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!

채택된 답변

Stephen23
Stephen23 2020년 10월 26일
편집: Stephen23 2020년 10월 26일
"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
Stephen23
Stephen23 2020년 10월 26일
편집: Stephen23 2020년 10월 26일
"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 2020년 10월 26일
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개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by