How to sort multiple text files by name in a struct

1 次查看(过去 30 天)
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