Dealing with leap years, creating arrays of yearly data
조회 수: 3 (최근 30일)
이전 댓글 표시
I have a time series in a Nx1 array where N are the number of days (different for each dataset, but lets take days from 1951 till 2007). Leap years are included (1952, 1956, ...). I am trying to convert the array into 366x57 (57 being the number of years between 1951-2007), by adding Nan at the Feb 29th (60th) position for non-leap years. I am sure there is a simple solution which I am having a hard time devising. Is there a way to accomplish this without loops.
댓글 수: 0
채택된 답변
the cyclist
2016년 4월 12일
Here is an example using two years, one leap and one not. Should be easy for you to see how to generalize.
% Time series with one leap year and one not
T = rand(365+366,1);
% The years
Y = 1951:1952;
numberYears = numel(Y);
% Slick way to identify the leap years
isLeapYear = datenum(Y,2,29)~=datenum(Y,3,1);
T_new = nan(366,numberYears);
for ny = 1:numberYears
numberDaysThisYear = 365+isLeapYear(ny);
T_new(1:numberDaysThisYear,ny) = T(1:numberDaysThisYear);
T(1:numberDaysThisYear) = []; % Deletes T as you go. Could do this differently
end
댓글 수: 3
the cyclist
2016년 4월 12일
I think I got the alignment right here, but you should double-check:
% Time series with one leap year and one not
T = rand(365+366,1);
% The years
Y = 1951:1952;
% Slick way to identify the leap years
isLeapYear = datenum(Y,2,29)~=datenum(Y,3,1);
numberYears = numel(Y);
T_new = nan(366,numberYears);
for ny = 1:numberYears
numberDaysThisYear = 365+isLeapYear(ny);
if isLeapYear(ny)
T_new(1:366,ny) = T(1:366);
else
T_new(1:59, ny) = T(1:59);
T_new(61:366,ny) = T(60:365);
end
T(1:numberDaysThisYear) = []; % Deletes T as you go. Could do this differently.
end
dpb
2017년 8월 13일
"% Slick way to identify the leap years"
My favorite is one of my standard utilities...
function is=isleapyr(yr)
% returns T for input year being a leapyear
is=eomday(yr,2)==29;
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!