I'm trying to convert date numbers to character dates, I created a vector using datenum and manually entering each date in Y,M,D,H,M,S format, and it works but I hope to find
5 次查看(过去 30 天)
显示 更早的评论
Hi I'm still a newbie, I'm trying to convert date numbers to character dates, I created a vector using datenum and manually entering each date in Y,M,D,H,M,S format, and it works BUT, I have a ton of files and it takes me forever to write and add to the vector each day in Y,M,D,H,M,S format, because I have to manually change each day everytime I run a different set of files.
This is what I have and it works:
dvec = [ datenum(2018,07,28,02,27,32); datenum(2018,07,28,19,18,50); datenum(2018,07,28,21,27,19); datenum(2018,07,28,14,08,06); ...];
I've been going over the documenation I could find and this is what I'm trying but it doesn't work (it just shows the last date in the struct):
DateNumber = daily_names.datenum;
formatOut = 'mm dd';
str = datestr(DateNumber,formatOut);
Ps.
daily_names is a struct with datenum as a column and what I'm ultimately trying to do, is to automatically have the X axis in a plot, show the dates of the data.
Thank you!! All advice is appreciated
1 个评论
回答(2 个)
Steven Lord
2022-2-3
Instead of using serial date numbers with datenum, use datetime.
% Arbitrary data. I entered this manually, but you could build these
% vectors automatically by reading from a file (for example) or using the
% normal vector creation tools like the colon operator (see y)
y = (2020:2022).';
mo = [6; 3; 11];
d = [4; 12; 1];
h = [4; 8; 5];
mi = [15; 16; 23];
s = [42; 20; 01];
T = datetime(y, mo, d, h, mi, s)
You can directly plot with datetime arrays.
plot(T, 1:3, 'o-')
0 个评论
Stephen23
2022-2-3
编辑:Stephen23
2022-2-3
As Steven Lord and Walter Roberson and the MATLAB documentation recommended, you should use DATETIME objects, which can be plotted directly (no need to convert to text).
You can simply convert your structure data like so:
T = datetime([daily_names.datenum], 'ConvertFrom','datenum', 'Format','MM dd')
Avoid using the less accurate, less versatile, deprecated functions DATENUM, DATEVEC, and DATESTR. The recommended DATETIME objects support many many functions and can be plotted directly: read the help to know more about them:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
