Saturday, February 25, 2012

[Matlab] create a time series using datenum

function myT=yymmdd2x(inYear,inMonth,inDay)
% create the time axis based on input time [year, mon, date], using datenum
% usage:
%           xTime=yymmdd2x(years, months, days);
% or
%           xTime=yymmdd2x(yyyymmdd);
http://scriptdemo.blogspot.com

if (nargin==0 || nargin>3)
   help yymmdd2x;
   return
end

if nargin==1
   %yyyymmdd case
   yyyymmdd=inYear;
   inYear=floor(yyyymmdd/10000);
   inDay=mod(yyyymmdd,100);
   inMonth=floor(mod(yyyymmdd,10000)/100); clear yyyymmdd
   totalDaysInYear=datenum(inYear+1,1,1)-datenum(inYear,1,1);
   daysInYear=datenum(inYear,inMonth,inDay)-datenum(inYear,1,1)+1;
   myT=daysInYear./totalDaysInYear+inYear;
elseif nargin==2
   % no date, set to 15th, may consider create 12 month for each year if necessary
   if length(inYear)~=length(inMonth) && length(inMonth)<=12
      % repeat inMonth for each year
      inMonth=reshape(inMonth,1,[]);
      mm=repmat(inMonth,1,length(inYear));
      yy=reshape(repmat(reshape(inYear,1,[]),length(inMonth),1),1,[]);
      clear inMonth inYear
      totalDaysInYear=datenum(yy+1,1,1)-datenum(yy,1,1);
      daysInYearA=datenum(yy,mm+1,1)-datenum(yy,1,1)+1;
      daysInYear=datenum(yy,mm,1)-datenum(yy,1,1)+1;
      myT=0.5*(daysInYearA+daysInYear)./totalDaysInYear+yy;

   elseif (length(inYear)==length(inMonth))
      totalDaysInYear=datenum(inYear+1,1,1)-datenum(inYear,1,1);
      daysInYearA=datenum(inYear,inMonth+1,1)-datenum(inYear,1,1)+1;
      daysInYear=datenum(inYear,inMonth,1)-datenum(inYear,1,1)+1;
      myT=0.5*(daysInYearA+daysInYear)./totalDaysInYear+inYear;
   else
       disp('Too difficult for me to guess what your wanna to do...')
       return
   end
else
   totalDaysInYear=datenum(inYear+1,1,1)-datenum(inYear,1,1);
   daysInYear=datenum(inYear,inMonth,inDay)-datenum(inYear,1,1)+1;
   myT=daysInYear./totalDaysInYear+inYear;
end

No comments:

ShowCalendar