How do I convert a cell array of character strings into datetime array efficiently?
조회 수: 4 (최근 30일)
이전 댓글 표시
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;
t=(datenum(txt{6:end,1})-datenum{6,1})*60^2*24
However, datenum returns a error claiming too many arguments. Next I tried to use cellfun to do the job;
t=(cellfun(@datenum,txt{6:end,1})-datenum(txt{6,1}))*60^2*24
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...
댓글 수: 0
채택된 답변
Peter Perkins
2018년 1월 17일
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
00:00:00
61:51:46
67:06:59
74:54:16
98:13:32
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.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!