New version of readtable reads dates as cell array rather than char
42 views (last 30 days)
Show older comments
I'm (2019a) having an issue where this code is behaving differently for myself and a coworker, who has a different version of matlab installed than I do (2021a). The goal of the code below is to get the final date associated with a data series as a character type and then get a month and year character variable from that.
Data = readtable('exampleMatlabIssue.xls','filetype','spreadsheet');
LastDate = table2array(Data{end,1});
LastYear = LastDate(1:4);
LastMonth = LastDate(end-1:end);
However when my coworker runs this code readtable returns a cell array in the first column rather than a char type array. I'm sure this has something to do with the new behavior of readtable since 2019b but just looking through the documentation its unclear to me what is driving the difference.
Ideally, we would both be able to run this code from our different versions and get the same output. I can think of a couple solutions to this problem but I'd like to understand the root of the issue since whatever is causing it will probably show up elsewhere in our dense web of code.
Potentially ir/relevant info: Using the "Format", "Auto" name-value pair causes him to get an error about file access + whether or not the file exists. The same happens when I try to import the data w/ the import tool on the actual data. I don't know if there's any possibility an excel setting is causing readtable to behavior differently.
0 Comments
Answers (1)
Cris LaPierre
on 16 Jul 2021
The autodetection capabilities of readtable are constantly improving. One way to ensure compatability across versions is to set variable type manually using setvartype.
Rather than work with strings, I would import the date as a datetime. You can then use the year and month functions to extract the information you need.
The following code gives me the same result in R2019b and R2021a.
opts = detectImportOptions('exampleMatlabIssue.xls');
opts = setvartype(opts,1,'datetime');
opts = setvaropts(opts,1,'InputFormat','yyyy:MM');
Data = readtable('exampleMatlabIssue.xls',opts)
LastDate = Data.Var1(end)
LastYear = year(LastDate)
LastMonth = month(LastDate)
0 Comments
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!