필터 지우기
필터 지우기

How to sort multiple text files by name in a struct

조회 수: 1 (최근 30일)
aggelos
aggelos 2016년 10월 22일
댓글: aggelos 2016년 10월 24일
Hi all,
I have a series of txt files which are read with dir as a structure but the sorting in like this:
'1-Apr-16.fullfeed'
'1-Aug-16.fullfeed'
'1-Feb-16.fullfeed'
'1-Jan-16.fullfeed'
'1-Jul-16.fullfeed'
'1-Jun-16.fullfeed'
'1-Mar-16.fullfeed'
'1-May-16.fullfeed'
'1-Oct-16.fullfeed'
'1-Sep-16.fullfeed'
'10-Apr-16.fullfeed'
'10-Aug-16.fullfeed'
'10-Feb-16.fullfeed'
'10-Jan-16.fullfeed'
'10-Jul-16.fullfeed'
'10-Jun-16.fullfeed'
'10-Mar-16.fullfeed'
'10-May-16.fullfeed'
'10-Sep-16.fullfeed'
'11-Apr-16.fullfeed'
'11-Aug-16.fullfeed'
'11-Feb-16.fullfeed'
'11-Jan-16.fullfeed'
How can I sort them to the correct date order?

답변 (1개)

Image Analyst
Image Analyst 2016년 10월 22일
편집: Image Analyst 2016년 10월 22일
This will do it:
% Define the cell array of filenames.
caFileNames = {...
'1-Apr-16.fullfeed'
'1-Aug-16.fullfeed'
'1-Feb-16.fullfeed'
'1-Jan-16.fullfeed'
'1-Jul-16.fullfeed'
'1-Jun-16.fullfeed'
'1-Mar-16.fullfeed'
'1-May-16.fullfeed'
'1-Oct-16.fullfeed'
'1-Sep-16.fullfeed'
'10-Apr-16.fullfeed'
'10-Aug-16.fullfeed'
'10-Feb-16.fullfeed'
'10-Jan-16.fullfeed'
'10-Jul-16.fullfeed'
'10-Jun-16.fullfeed'
'10-Mar-16.fullfeed'
'10-May-16.fullfeed'
'10-Sep-16.fullfeed'
'11-Apr-16.fullfeed'
'11-Aug-16.fullfeed'
'11-Feb-16.fullfeed'
'11-Jan-16.fullfeed'}
months = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'};
daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
% Turn each filename into a day of the century.
for k = 1 : length(caFileNames)
% Split filename apart into pieces.
theseWords = strsplit(caFileNames{k}, '-');
% Determine what month number it is.
[ia, monthNumber] = ismember(theseWords{2}, months);
% See what day of the current year it is.
if monthNumber == 1
dayOfYear = str2double(theseWords{1});
else
dayOfYear = sum(daysPerMonth(1:monthNumber-1)) + str2double(theseWords{1});
end
% Determine what day of the century it is.
dayOfCentury(k) = str2double(theseWords{3}(1:2)) * 356 + dayOfYear;
end
[sortedDays, sortOrder] = sort(dayOfCentury, 'ascend');
% Get the final sorted cell array
new_ca = caFileNames(sortOrder)
I bet Stephen Cobeldick would change his program to handle that if you contact him.
  댓글 수: 1
aggelos
aggelos 2016년 10월 24일
Hi and thank you for your answer.
It seems that the for loop is just splitting the last file name and not looping thought the whole set.
I read that loop for cell arrays is looping through columns and not rows

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by