我每天都有' .mat'文件的命名类似于' Data_grid_day_ppt_ice003.mat',最后的''是朱利安日格式的年份日期,它可以从' 001'开始。并以' 365'结束和' 366'取决于它是否是闰年。
我需要每月平均数据。知道如何为日期文件创建循环?
某些日期也可能丢失,因此仅计算文件数量将无效。
我在Matlab写作,我正在尝试像
这样的东西year = linspace(2007,2016,10); % Years of data
months = linspace(01,12,12);% Months of the year
for n = 1:length(year)
foldery = int2str(year(n));
if ~exist(folderyear)
continue
else
if mod(year,4) == 0 % if the year is divisible by four
dpm = [31 60 91 121 152 182 213 244 274 305 335 366];
else
dpm = [31 59 90 120 151 181 212 243 273 304 334 365];
end
for j = 1:length(months) %loop over months
if ~exist(months)
continue
else
for ii = 1:dpm(j) %loop over days
% ... Not sure what to do here ...
end
end
end
end
end
但是,我无法完成下一步......
答案 0 :(得分:0)
首先,不要使用year
作为变量名,因为它是内置的Matlab函数!然后小心使用变量名称,例如混淆foldery
和folderyear
。
最简单的方法是将一年中的某一天添加到该年的1月1日,然后使用内置month
功能的Matlab获取月份。只要您知道这一年(您似乎),这将照顾所有闰年问题。另请参阅此文档Date and Time Arithmetic,该文档确认在日期时间值中添加数字将添加完整的24小时日。
关键是这种方法可以从一年中的Julian日算起一个月:
thisyear = 2017; % Define which year you're in
J1 = datetime(2016,1,1); % Set January first datetime
dayofyear = 360; % Christmas day as an example!
m = month(J1 + dayofyear - 1) % Add day of year to Jan 1st, get month
% J1 + dayofyear - 1 = 25-Dec-2016 00:00:00
% m = 12
% month(J1 + dayofyear - 1, 'name') = 'December'
有关更多详细信息,请参阅此代码的注释扩展...
y = 2007:2016; % Years of data [2007, 2008, ... 2016]
outputdata = cell(1,12);
for n = 1:length(y)
folderyear = int2str(y(n));
if ~exist(folderyear, 'dir')
continue
else
% Get all .mat files within this year folder
f = dir(fullfile(folderyear, '*.mat'));
filenames = {f.name};
% Set Jan 1st date
J1 = datetime(y, 1, 1);
% Loop over months
for m = 1:12
% Loop over files
for myfile = 1:numel(filenames)
% Get number from end of file name
dayofyear = filenames{myfile};
dayofyear = str2num(dayofyear(end-6:end-4));
% Get month of day by adding to Jan 1st of that year
% -1 used assuming Jan 1st is day 1. Not needed if Jan 1st is day 0.
if month(J1 + dayofyear - 1) == m
% hurrah, this file is in the month m, add it to an average
% or anything else you want, then you could assign to
% an output cell or matrix
% outputdata{m} = ...
end
end
end
end
end
答案 1 :(得分:0)
如果我做Num = regexp(dayofyear,'\d','Match');
tt=cellstr(Num{:});
pp = strcat(tt(1),tt(2),tt(3));
dayofyear=str2double(pp);
现在即将到来虽然它有点幼稚,但如果我在一行中这样做会返回错误:P Thanku Wolfie:)