Changing arrays to date format

Hi everyone, I have 4 arrays that represent year, day, hour and minute. How can I put it in date format so that I can plot my data in terms of time in the x axis? Thanks.

 Accepted Answer

You can use serial date numbers. I will assume here, given that you did not mention month, that the day is "day number of the year".
z = zeros(numel(YearArray),1);
xdates = datenum( [YearArray(:), z, DayArray(:), HourArray(:), MinuteArray(:), z] );
plot(xdates, y)
datetick('x', 'mmm dd'); %month and day, for example. Notice datenum month is lower case m
If you have R2014b or newer you can use datetime objects, which are a little easier to plot with as you can use them directly on the x axis. However, it also turns out to be a bit messier to create vectors from day numbers
z = zeroes(numel(YearArray),1);
z1 = ones(numel(YearArray),1);
xdates = datetime( [YearArray(:), z1, z1, HourArray(:), MinuteArray(:), z] ) + days(DayArray(:) - 1);
xdates.Format = 'MMM dd'; %month and day, for example. Notice datetime month is upper case m
plot(dates, y)

3 Comments

Thank you so much Walter. I have R2009 so the first method works best for me.
Walter,
I have tried the first method and the result I am getting is like this. xdates =
1.0e+005 *
7.304860000000000
7.304860006944444
7.304860013888889
7.304860020833333
7.304860027777777
the year is supposed to be 2000, day 1, hour 0, minute 0,1,2,3,4. Is there a different way of displaying it? Thank you.
format long g
However that will not be very instructive, you will find.
There is no different way of displaying it that will make any more sense. However, you can convert the serial date numbers to strings using datestr() and display the strings. You need to pass the numeric forms to plot(), though.
>> datestr(1E5*[7.304860000000000
7.304860006944444
7.304860013888889
7.304860020833333
7.304860027777777])
ans =
01-Jan-2000 00:00:00
01-Jan-2000 00:01:00
01-Jan-2000 00:02:00
01-Jan-2000 00:03:00
01-Jan-2000 00:04:00

Sign in to comment.

More Answers (0)

Categories

Tags

Community Treasure Hunt

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

Start Hunting!