Unrecognized variable when using delimitedT​extImportO​ptions

5 vues (au cours des 30 derniers jours)
Mikel Cotillas
Mikel Cotillas le 29 Oct 2022
Commenté : Campion Loong le 17 Nov 2022
I followed the example in the documentation for the command "delimitedTextImportOptions" to import from a file with a variable that I explicitly named "fecha":
varNames = ["ccaa_iso","fecha","num_casos","num_casos_prueba_pcr","num_casos_prueba_test_ac","num_casos_prueba_otras","num_casos_prueba_desconocida"];
varTypes = ["char","datetime", "int32", "int32", "int32", "int32", "int32" ];
delimiter = ",";
dataStartLine = 2;
extraColRule = "ignore";
opts = delimitedTextImportOptions("VariableNames", varNames, "VariableTypes", varTypes, "Delimiter", delimiter, "ExtraColumnsRule", extraColRule);
datosccaas26122020 = readtable("datos_ccaas_26-12-2020.csv", opts);
But then when I try to use the following command:
dies = datestr(fecha, "yyyymmdd");
it throws an error, telling me that fecha is not a recognized variable. But if I simply right-click on the .csv file and use the GUI to import the data, it then can read the variable fecha. So what's happening here?
  2 commentaires
Stephen23
Stephen23 le 29 Oct 2022
Forcing meta-data (i.e. the timestamp) into the variable name is unlikely to be a good approach:
datosccaas26122020 = readtable(..)
Much better would be to use a name without meta-data in it, e.g.:
tbl = readtable("datos_ccaas_26-12-2020.csv", opts);
dies = datestr(tbl.fecha, "yyyymmdd");
Mikel Cotillas
Mikel Cotillas le 30 Oct 2022
Thank you too for the answer!

Connectez-vous pour commenter.

Réponse acceptée

Voss
Voss le 29 Oct 2022
fecha would be a variable (i.e., a column) in the table datosccaas26122020, so the syntax would be:
dies = datestr(datosccaas26122020.fecha, "yyyymmdd");
  3 commentaires
Voss
Voss le 1 Nov 2022
You're welcome!
Campion Loong
Campion Loong le 17 Nov 2022
On separate note, as the table variable "fecha" is a datetime, datestr is not recommended for turning it into text any more. You can use either char or string (i.e. note the upper case "M" versus lower case "m" - datetime conforms to the Unicode standard):
dies = string(datosccaas26122020.fecha, "yyyyMMdd");

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by