Clear Filters
Clear Filters

How to sort multiple text files by name in a struct

1 view (last 30 days)
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?

Answers (1)

Image Analyst
Image Analyst on 22 Oct 2016
Edited: Image Analyst on 22 Oct 2016
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 Comment
aggelos
aggelos on 24 Oct 2016
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

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!