Sorting problem with months in file names, while taking average

조회 수: 2 (최근 30일)
Venkata
Venkata 2018년 10월 16일
댓글: Venkata 2018년 10월 17일
When I read the file names from a selected directory, the names are coming out to be like the following:
I tried
folder_path=uigetdir;
cd(folder_path)
flist=dir('*.dat');
flist.name gives
A01-Apr-2014.dat
A01-Apr-2015.dat
A01-Apr-2016.dat
A01-Aug-2014.dat
A01-Aug-2015.dat
A01-Aug-2016.dat
A01-Dec-2014.dat
A01-Dec-2015.dat
A01-Dec-2016.dat
....
Is there a way in MATLAB to read and access the file names in the actual month order?
E.g:
A01-Jan-2014.dat
A01-Feb-2014.dat
A01-Mar-2014.dat
A01-Apr-2014.dat
...
A01-Jan-2015.dat
A01-Feb-2015.dat
A01-Mar-2015.dat
....
Then, taking hourly averages from each month and writing the entire average values in a single file would be easy and flawless.
Thank you.

채택된 답변

Stephen23
Stephen23 2018년 10월 16일
편집: Stephen23 2018년 10월 16일
Two solutions:
1) Use ISO 8601 dates in the filenames, then they can be sorted using a trivial character sort.
2) Convert those dates to date numbers, sort them, and then apply those indices to the filenames. Like this:
C = {flist.name};
V = datenum(C,'Add-mmm-yyyy.dat');
[~,idx] = sort(V); % sort the date numbers.
C = C(idx); %sort the filenames into date order.
for k = 1:numel(C)
C{k} % filename
...
end
  댓글 수: 13
Stephen23
Stephen23 2018년 10월 17일
편집: Stephen23 2018년 10월 17일
@Venkata: here are two solutions:
1) use format '%g', e.g. '%10.5g', or something similar.
2) write the file using fprintf and define your own format string.
Read the fprintf help to know how to define dlmwrite's precision format string, and of course the fprintf format string.
Venkata
Venkata 2018년 10월 17일
@Stephen: Thanks a ton for your help and time.
Sure, I did mark it as accepted answer and voted too :).
I make sure that, I properly acknowledge and respect the people who helped me in my tough time, especially.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by