Converting yyyymmdd double to decimal year
9 次查看(过去 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!