Create a time vector

10 views (last 30 days)
Derol sakpak
Derol sakpak on 18 Dec 2021
Answered: Siddharth Bhutiya on 30 Dec 2021
Hello. I have a problem with my data matrix In fact I have daily data of SST 3D 60*50*14184, respectively longi latitude and sst of which I would like to create a date vector of the type DD/MM/YY of dimensions 14184 only by doing datenum([1979 1 1]):datenum([2017 10 1]) I get a dimension of 14154 yet my data goes exactly from 01/01/1979 to 01/10/2017.Need help please to keep my time vector exactly on schedule. THANK YOU

Accepted Answer

Chunru
Chunru on 18 Dec 2021
t0 = datenum([1979 1 1 0 0 0])
t0 = 722816
n = 14184; % or 14154
t = t0 + (0:n-1);
% Show part of the vector
datestr(t(end-5:end))
ans = 6×11 char array
'26-Oct-2017' '27-Oct-2017' '28-Oct-2017' '29-Oct-2017' '30-Oct-2017' '31-Oct-2017'

More Answers (1)

Siddharth Bhutiya
Siddharth Bhutiya on 30 Dec 2021
For dates and time related workflows, you should avoid using legacy functionality like datenum, datestr,etc and use more modern types like datetime. This would make your life a lot easier and avoid the common pitfalls of the older functionality.
Now you mentioned that you get 14154 values, that is because there are 14154 days from Jan 1 1979 to Oct 1 2017, so if you create a vector of dates that increment by 1 day then you should get 14154 values. So as mentioned in the answer above, if you need 14184 values then you need to go to Oct 31 2017.
So if you want to generate a datetime vector from one date to another you can do this as follows
>> dt = datetime([1979 1 1]):datetime([2017 10 31]);
>> size(dt)
ans =
1 14184
>> dt(end-5:end)
ans =
1×6 datetime array
26-Oct-2017 27-Oct-2017 28-Oct-2017 29-Oct-2017 30-Oct-2017 31-Oct-2017
If you would like to create a datetime vector that starts from a particular date (like Jan 1 1979 in your case) and then increments by one day and goes on for the specified number of days, then you could do something like the following
>> dt = datetime([1979 1 1]) + (0:14183);
>> dt(1:5)
ans =
1×5 datetime array
01-Jan-1979 02-Jan-1979 03-Jan-1979 04-Jan-1979 05-Jan-1979
>> dt(end-5:end)
ans =
1×6 datetime array
26-Oct-2017 27-Oct-2017 28-Oct-2017 29-Oct-2017 30-Oct-2017 31-Oct-2017

Categories

Find more on Dates and Time in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!