MATLAB: Averaging files with different dates

averagedatestxt

hi! I have files from 1978 to 2009 every 10 days, named as follows:
1978_11.txt
1978_21.txt
. . .
2009_361.txt
2009_365.txt
I would like to average the day 11 of every year and generate a file, then the day 21 and so on, but I dont know how.
I know how to read the files (they are in the same folder, but not how to read the ones I know for the average… Can someone help me please?
thank you for your time

Best Answer

years = 1978:2009
for y = years
pattern = sprintf('*_%d.txt', y);
d = dir(pattern);
Nfiles = numel(d);
average = 0;
for i = 1:numel(d)
filename = d(i).name;
% read data from filename
% insert your function here
% assume that the data is read into variable 'data'
average = average + 1/Nfiles*data;
end
average_filename = sprintf('avg_%d.txt', y);
% write data to file, e.g., using dlmwrite
dlmwrite(average_filename, average)
end