Converting dates into numbers

1 visualizzazione (ultimi 30 giorni)
Sergio
Sergio il 10 Set 2013
Risposto: Peter Perkins il 12 Set 2018
I have a int32 matrix of dates in the format YYYYMMDD and a cell array for time in the day in the format HH:MM. How can I combine both and turn it into a number I can use for plotting?

Risposta accettata

Azzi Abdelmalek
Azzi Abdelmalek il 10 Set 2013
x=int32([19921212,19921213,19921214])'
y={'12:12', '13:13','14:14'}'
a=[num2str(x) char(y)]
b=datenum(a,'yyyymmddHH:MM')
datestr(b)
  3 Commenti
Silver
Silver il 11 Set 2018
@Azzi and when I have the date format already sticked together like this: 2016.03.01 14:38:00 in a cell array how can I convert them to numeric so I can ue them in plot ? thks in advance
Stephen23
Stephen23 il 11 Set 2018
@Silver: read the datenum documentation.

Accedi per commentare.

Più risposte (1)

Peter Perkins
Peter Perkins il 12 Set 2018
Unless you're using a fairly old version of MATLAB, consider using datetimes instead of datenums. You will be happier.
>> x = int32([19921212,19921213,19921214])';
>> y = {'12:12', '13:13','14:14'}';
>> d = datetime(x,'ConvertFrom','yyyymmdd')
d =
3×1 datetime array
12-Dec-1992 00:00:00
13-Dec-1992 00:00:00
14-Dec-1992 00:00:00
>> t = duration(y,'InputFormat','hh:mm')
t =
3×1 duration array
12:12:00
13:13:00
14:14:00
>> dt = d + t
dt =
3×1 datetime array
12-Dec-1992 12:12:00
13-Dec-1992 13:13:00
14-Dec-1992 14:14:00
Then just plot whatever vs. dt. You don't need to convert the datetimes to numeric.
Actually, creating the duration directly form text requires R2018a, prior to that do this:
>> t = timeofday(datetime(y,'InputFormat','HH:mm'))
t =
3×1 duration array
12:12:00
13:13:00
14:14:00
or use text2duration on the File Exchange.

Categorie

Scopri di più su Dates and Time in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by