How do I convert a cell array of character strings into datetime array efficiently?

11 views (last 30 days)
I have a cell array of character strings which contains column headers and my time stamp information we will call txt. I want to be able to efficiently extract the timestamp column and convert it to seconds. counting up from zero at the first entry. I tried to use datenum as follows;
However, datenum returns a error claiming too many arguments. Next I tried to use cellfun to do the job;
However, this returns an error on cellfun saying input #2 was expected to be a cell array but was char instead. Surely there is a more elegant way than setting up a loop to march through and do it line by line...

Accepted Answer

Peter Perkins
Peter Perkins on 17 Jan 2018
There is a more elegant way, and stop calling me Shirley.
The thing you're passing into datenum, c{6:end,1}, is a list of values, known as a "comma separated list". What you wanted there was c(6:end). But also, you should consider using datetime instead of datenum.
>> c = {'a';'b';'15-Jan-2018 10:55:59';'18-Jan-2018 00:47:45';'18-Jan-2018 06:02:58';'18-Jan-2018 13:50:15';'19-Jan-2018 13:09:31'}
>> d = datetime(c(3:end));
>> dt = d - d(1)
dt =
5×1 duration array
and perhaps
>> dt.Format = 's'
dt =
5×1 duration array
0 sec
2.2271e+05 sec
2.4162e+05 sec
2.6966e+05 sec
3.5361e+05 sec
Also, it sounds like the cell array you have has names in its first row, and the rest of the roes are data. You might be happier using a table.

More Answers (0)


Find more on Matrices and Arrays 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!