Order CSV based on underlying timestamp OR using correct number

조회 수: 13 (최근 30일)
Robin L
Robin L 2021년 2월 16일
편집: Stephen23 2021년 4월 18일
We extracted data using LabVIEW and got these kind of files:
For this measurement we have 151 files. But when I try to read them using this code:
%% declare folder containing the files
d = uigetdir(pwd, 'Select a folder');
csvFiles = dir(fullfile(d, '*.csv')); % get all csv files
% csvFilesOrdered = natsortfiles({csvFiles.name});
I tried ordering it through natsortfiles function but this does not work. What we get is:
Is there an easy way to solve this so it reads the files in the correct order? There should be a way to easily extract this but I cannot find it.
Thanks in advance!
  댓글 수: 1
Stephen23
Stephen23 2021년 2월 17일
편집: Stephen23 2021년 4월 18일
"I tried ordering it through natsortfiles function but this does not work."
natsortfiles now directly sorts the output from DIR:
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'

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

채택된 답변

Robin L
Robin L 2021년 2월 17일
Fixed it using:
[r inx]=sort({csvFiles.date});
csvFiles = csvFiles(inx);
  댓글 수: 3
Robin L
Robin L 2021년 2월 17일
편집: Robin L 2021년 2월 17일
It gives me the csvFiles 1x151 struct in the correct order like this:
So I think that is enough? I now get the expected results on the graph.
EDIT: I think sorting the way you did would give the same result.
Stephen23
Stephen23 2021년 2월 17일
편집: Stephen23 2021년 2월 17일
"I think sorting the way you did would give the same result."
Not at all.
The way I showed you in my comment sorts the filenames alphanumerically.
Your approach will sort August before February, and the 1st of any month in 2021 before the 2nd of any month in 2020. Have you considered what it really means to sort the character vectors of the date field?
If the dates were given in an ISO 8601 format then your approach would give a robust sort order (by file modification date), but they aren't, so in general the order is not meaningful. Using the datenum field would be robust.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by