Benjamin Levy
Benjamin Levy

Reputation: 343

How can I parse a cell array of date strings with irregular lengths in MATLAB?

I have a cell array of dates as strings (format: 'mm/dd/yyyy'), where the string length varies by cell entry from 8 to 10, depending on the date (e.g., n = 8 for '1/1/2015' and n = 10 for '10/10/2015'). I want to convert each cell array entry to its corresponding double as a datenum quantity. I've tried:

id = find(~cellfun( @isempty, regexp( dateList, '/', 'tokenExtents' ) ) );

and

id = find(~cellfun( @isempty, strfind( dateList, '/' ) ) );

but this isn't right. A snippet of the cell array is provided:

dateList = {'9/9/2016';
            '9/10/2016';
            '10/10/2016';
            '10/11/2016'};

Upvotes: 1

Views: 131

Answers (2)

Squeezie
Squeezie

Reputation: 361

1) Extract each cell to 3 different blocks with strsplit: day,month and year

2) Use pad to make each block the same length (2 for day and month and 4 for year)

3) Join the string together with [D,'/',M,'/',Y] and you are able to run datenum without problem.

Edit 1: I think the other answer is far more easy, I didn't know datenum can take strings with slightly different foramt.

Upvotes: 0

gnovice
gnovice

Reputation: 125854

All you have to use is datenum, since it will accept a cell array of strings:

dateList = {'9/9/2016'; '9/10/2016'; '10/10/2016'; '10/11/2016'};
id = datenum(dateList);

And to confirm it worked:

>> datestr(id)

ans =

09-Sep-2016
10-Sep-2016
10-Oct-2016
11-Oct-2016

Upvotes: 3

Related Questions