Search code examples
matlabdatetimeplotmatlab-figure

Working with dates in MATLAB


How can I get MATLAB to display the dates and times on the x-axis of a plot?

I am trying to make a plot that shows the water level (WL) in cm over time, as illustrated in the image:

Water level over time. indices on x-axis, water level on y-axis

Right now, the x-axis of my plot just shows indices, but I want it to display the dates and times in the order: year, month, day, hour, minute. The format is not that important as long as it's readable and in that order. I also want to be able to control the ticks, so that the user won't be overwhelmed.

In MATLAB, I've been working with dates in the following way:

  1. An array that contains the DATES in yyyyMMddhhmm format as numbers.
  2. Multiple arrays that contain yyyy, MM, dd and so on.

WL and my DATES array have the same length, and they arranged so that WL(i) corresponds to DATES(i). Right now, my code looks like this:

figure(1)
hold on
plot(WL)
xlabel('Date')
ylabel('WL [cm]')

Solution

  • Assuming your WL and DATES looks like this:

    WL = [6 4 5];
    DATES = [201412241842
        201412251830
        201412261921];
    

    You can do the following to convert DATES to datetime format:

    dates = datetime(num2str(DATES),'InputFormat','yyyyMMddHHmm');
    

    And then you just plot it:

    plot(dates,WL)
    

    enter image description here