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 Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by