如何在 MATLAB 中将日期整数数组转换为“datenum”对象?

How to convert array of date integers to `datenum`objects in MATLAB?

我有一堆这样的日期整数:

dates_array = [20060828 ,20060831 , 20060901];

而且,我想将它们用作绘图的 x 轴。所以,我尝试像这样转换它们:

datecells = [];
for datecell=dates_array
    display(datecell)
    dn = datenum(char(datecell), 'YYYYmmdd');
    datecells = [datecells, dn];
end

我从 this 了解到这些 dn 应该是天数。没关系。但是当我打印出 datecells 变量时,这就是我得到的,我不知道为什么:

>> datecells

datecells =

      736696      736696      736696

为什么这三个元素显示的天数相同?

空元胞数组定义如下:

datecells={};

现在,将每个元素转换为格式并将其添加到单元格的末尾。

formatOut = 'dd mmm yyyy';
for i=1:3
     dt = datestr(datenum(char(dateArray[i]), 'YYYYmmdd'),formatOut);
     datecells(end+1)= dt
end

我还没有测试代码。

在修改 dates_array 以提取 year/month/day 组件后,您可以使用三参数 datenum 语法。

% use a combination of MOD and floored division to extract
% year-month-day components
ymd = floor(bsxfun(@rdivide, bsxfun(@mod, dates_array, ...
    [1e8; 1e4; 1e2]), [1e4; 1e2; 1]));
% ymd is now a matrix where the 1st row is year, 2nd row is
% month, and 3rd row is day of month
dates = datenum(ymd(1,:), ymd(2,:), ymd(3,:));