Behzad
Behzad

Reputation: 49

How to generate a date-time array in MATLAB?

How do I generate this 480x1 array of date-times in Matlab?

1982-01-01
1982-02-01
1982-03-01
1982-03-01 
1982-04-01
.
.
.
2015-12-01

Upvotes: 1

Views: 2047

Answers (1)

SecretAgentMan
SecretAgentMan

Reputation: 2854

This is made easy with the datetime function (introduced in R2014b) and following the documentation to Generate Sequence of Dates and Time.

% MATLAB 2019a
t1 = datetime(1982,1,1);
t2 = datetime(2015,12,1);
t = t1:t2;
t = t(:);      % Force column

Alternatively, you can specify the number of linearly-spaced points between two dates using the linspace command.

t_alt = linspace(t1,t2,480).';

You can convert to the y-M-d format you specified with datetime as well.

t_format = datetime(t,'Format','y-M-d')

References:
1. Dates and Time (in MATLAB)
2. Represent Dates and Times in MATLAB
3. Set Date and Time Display Format
4. Generate Sequence of Dates and Time

Upvotes: 3

Related Questions