SugaKookie
SugaKookie

Reputation: 790

MATLAB Change numbers to date

I have time set up as serial dates. Each number corresponds to a day, in order, from 20100101 to 20130611. How do I convert the serial date to a date in the format month-year? I need this because I want to plot data and need the x axis to show the date.

Thanks!

Upvotes: 0

Views: 4627

Answers (2)

Martin J.H.
Martin J.H.

Reputation: 2205

The first step is to convert your date-format into one of the standard Matlab date formats. The best format to use for plots is the "serial date format". The numbers itself are a bit awkward, since they represent the "amount of time after 0/0/0000, in days", which is a huge number. Also, this date actually never existed, making it really weird when you want to work with dates that are BC.

However, the conversion is easy, since your format also counts the days, but you count after 31st of December, 2009. You can convert this using

numeric_date_vec = datenum(2009, 12, 31) + x;

You then plot your data using

plot(numeric_date_vec, y)

and you let Matlab add the date-ticks automatically by calling

datetick('mmm yyyy')

The problem is, the ticks do not update after zooming in. You can either call

datetick('mmm yyyy','keeplimits')

again, after each zooming or panning, or you download datetickzoom from the Matlab file exchange. It takes the same arguments as datetick, but it hooks into the zoom function and updates the ticks automatically.

Edit:

Sometimes, the dateticks are not spaced in any sensible way, then you can either try to zoom in and out a little until it snaps to something good, or you have to set the ticks manually:

% Set ticks to first day of the months in 2010
tick_locations = datenum(2012,[1:12],1);
% Set ticks on x-axis
set(gca, 'XTick', tick_locations)
% Call datetick again to get the right date labels, use option "keepticks"
datetick('mmm yyyy','keeplimits', 'keepticks')

You might have to modify the tick_locations = datenum(2012,[1:12],1) a bit to get the ticks that you want. For instance, you can use

tick_locations = datenum(2012,[1:2:25],1)

to get every second month between Jan 2012 and Jan 2013.

Upvotes: 2

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

For day number n use

datestr(datenum(2009, 12, 31) + n, 'yyyy-mm')

for example

>> datestr(datenum(2009, 12, 31)+365, 'yyyy-mm')
ans =
2010-12

>> datestr(datenum(2009, 12, 31)+366, 'yyyy-mm')
ans =
2011-01

Upvotes: 0

Related Questions