How can I convert a cell array of "random dates in the year" into time in year?

For ex: My input vector has random dates like 1993-4-1,1993-4-28 etc.Output should be 1993.000,1993.0039,1993.0078.I have used different functions (datevector, datenum etc). But they convert the date either to date numbers (730990) or yr month day format; not in the above output form. Btw I have to extract the input array from a .mat file. Thanks...

 Akzeptierte Antwort

One possibility:
datestrs = {'1993-4-1'; '1993-4-28'}; % Date String Cell Array
dnvct = datenum(datestrs, 'yyyy-mm-dd'); % Convert To Date Numbers
dateyr = str2num(datestrs{1}(1:4)); % Get Year (Numeric)
range_yr_dn = datenum([dateyr 1 1 0 0 0; dateyr 12 31 23 59 59]); % Start, End Of Year
range_yr_dn_diff = diff(range_yr_dn); % Year Range
year_fraction = (dnvct - range_yr_dn(1))./range_yr_dn_diff; % Year Fraction For Each Input Date
Result = [repmat(dateyr, size(year_fraction,1), 1) + year_fraction] % Year Fraction In Desired Format
Result =
1993.2
1993.3

Weitere Antworten (1)

Matt J
Matt J am 4 Okt. 2015
Bearbeitet: Matt J am 4 Okt. 2015
Here's a way using datetime,
>> yourDates=datetime({ '1993-4-1','1993-4-28'},'InputFormat','yyyy-M-d')
yourDates =
01-Apr-1993 28-Apr-1993
>> doy=day(yourDates,'dayofyear');
>> [Y,M,D]=ymd(yourDates); M(:)=12; D(:)=31;
>> doyDec31=day(datetime(Y,M,D),'dayofyear');
>> result=Y+doy/doyDec31;

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by