Converting yyyymmdd double to decimal year
조회 수: 8 (최근 30일)
이전 댓글 표시
Hi there, I have many variables made from doubles. I would like to plot certain variables against the date which is also made of doubles in the format yyyymmdd. So far i have:
function [out1] = simpleplot(variable,depthvar,mindepth,maxdepth,datevar,startdate,enddate,xlab,ylab);
depth = find(depthvar>mindepth & depthvar<maxdepth & ~isnan(variable));
datedepth=datevar(depth);
variable_depth=variable(depth);
plot(datedepth, variable_depth,'sk--')
xlabel(xlab);
ylabel(ylab);
axis([startdate enddate min(variable_depth) max(variable_depth)]);
end
However because my dates are yyyymmdd not in decimal year the plot has large gaps in it.
How can i convert the date doubles to decimal year within the function and also to have the x axis show date in a meaningful way like yy/mm rather than decimal year.
thank-you
댓글 수: 0
채택된 답변
Guillaume
2016년 2월 14일
편집: Guillaume
2016년 2월 14일
An alternative to the conversion to string and back, which is always going to be slow, is to divide and mod you date variable:
datevar = [19981020 19981023 19981203 1999011];
y = floor(datevar/10000);
m = floor(mod(datevar, 10000) / 100);
d = mod(datevar, 100);
datedepth = datetime(y, m, d);
추가 답변 (1개)
Star Strider
2016년 2월 14일
To get MATLAB date numbers from your date data, this works:
date_var = 20160214;
date_number = datenum(sprintf('%.0f', date_var), 'yyyymmdd');
Check = datestr(date_number)
Check =
14-Feb-2016
댓글 수: 3
Star Strider
2016년 2월 14일
My pleasure.
I was illustrating the idea. To use my code on a column vector of double-precision dates, it needs to be tweaked a bit:
double_date_vec = [20160214:20160313]'; % Column Vector Of Double-Precision Dates
date_number_fcn = @(double_dates) datenum(sprintf('%.0f\n', double_dates), 'yyyymmdd');
date_nums = arrayfun(date_number_fcn, double_date_vec);
Check = datestr(date_nums(1:20,:)) % Check Output (Can Be Deleted)
The date_nums array contains the datenum date numbers for all the dates in the ‘double_date_vec’ column vector. The arrayfun call does the background looping (much more efficiently than a for loop) necessary to apply the ‘date_number_fcn’ function to the vector of double-precision date variables. The MATLAB date and time functions do all the necessary conversions, including in this instance to allow for 2016 being a leap year.
I usually include ‘Check’ variables to illustrate that my code does what it needs to. Here, it prints 14-Feb-2016 to 04-Mar-2016 to the Command Window. You can discard that line.
참고 항목
카테고리
Help Center 및 File Exchange에서 Calendar에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!