MATLAB Answers

New version of readtable reads dates as cell array rather than char

조회 수: 4(최근 30일)
Chris de Mena
Chris de Mena 2021년 7월 16일
답변: Cris LaPierre 2021년 7월 16일
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.


Cris LaPierre
Cris LaPierre 2021년 7월 16일
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)
Data = 85×2 table
Var1 PRICES _______ ________ 1977:12 0.6759 1978:01 0.15867 1978:02 0.042329 1978:03 0.47476 1978:04 0.26499 1978:05 0.22857 1978:06 0.47078 1978:07 0.010721 1978:08 0.47129 1978:09 0.71064 1978:10 0.11498 1978:11 0.37446 1978:12 0.35039 1979:01 0.58482 1979:02 0.6792 1979:03 0.88049
LastDate = Data.Var1(end)
LastDate = datetime
LastYear = year(LastDate)
LastYear = 1984
LastMonth = month(LastDate)
LastMonth = 12

Community Treasure Hunt

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

Start Hunting!

Translated by