How to sort multiple text files by name in a struct

1 visualizzazione (ultimi 30 giorni)
aggelos
aggelos il 22 Ott 2016
Commentato: aggelos il 24 Ott 2016
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?

Risposte (1)

Image Analyst
Image Analyst il 22 Ott 2016
Modificato: Image Analyst il 22 Ott 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 Commento
aggelos
aggelos il 24 Ott 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

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by