Convert column of matrix from double to date MM/dd/yyyy using datetime

8 visualizaciones (últimos 30 días)
Caroline Lu
Caroline Lu el 28 de Mzo. de 2019
Editada: Stephen23 el 28 de Mzo. de 2019
I have scoured the datetime documentation to figure out if my syntax is wrong, but it seems correct to me.
I have a matrix called x with the format:
x = [12/31/2018 3.76667
12/31/2018 3.81667
12/31/2018 4.15
12/31/2018 4.41667
12/31/2018 4.71667]
I am trying to convert the first column into a date format so that I can plot the matrix.
datestr = num2str(x(:,1));
d = datetime(datestr,'InputFormat','MM/dd/yyyy');
However, I get the following error:
Error using datetime (line 635)
Unable to convert the text to datetime using the format 'MM/dd/yyyy'.
Error in Dates (line 161779)
d = datetime(datestr,'InputFormat','MM/dd/yyyy');
As far as I can tell from the documentation, 'MM/dd/yyyy' is a valid format. Any ideas? Have attached the file for reference.
  2 comentarios
Stephen23
Stephen23 el 28 de Mzo. de 2019
Editada: Stephen23 el 28 de Mzo. de 2019
@Caroline Lu: both your example "matrix" and the uploaded file define x in the same way:
x = [12/31/2018 3.76667
12/31/2018 3.81667
12/31/2018 4.15
12/31/2018 4.41667
12/31/2018 4.71667]
There is no attempt to define x as string or as a cell array of character vectors. Which means both cases simply define a numeric matrix by dividing some numbers:
>> x = [12/31/2018 3.76667
12/31/2018 3.81667
12/31/2018 4.15
12/31/2018 4.41667
12/31/2018 4.71667]
x =
0.000191821989194028 3.76667
0.000191821989194028 3.81667
0.000191821989194028 4.15
0.000191821989194028 4.41667
0.000191821989194028 4.71667
That numeric matrix contains no strings or character vectors, so it certainly does NOT contain any formatted dates. And the numbers in the first column are essentially meaningless, so there is little point in converting them character using num2str:
>> num2str(x(:,1))
ans =
0.00019182
0.00019182
0.00019182
0.00019182
0.00019182
Note that as soon as you divide 12 by 31 and then the result by 2018 you have lost any information that uniquely identifies those dates. The matrix you have shown us is NOT suitable for storing dates.
Note that naming a variable datestr is a bad idea, as this shadows the inbuilt function of the same name (and which you are likely to want to use if you are working with dates).
Walter Roberson
Walter Roberson el 28 de Mzo. de 2019
12/31/2018 means to divide 12 by 31, and then divide the result by 2018.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by