How to handle empty strings with datenum

조회 수: 6 (최근 30일)
David K
David K 2018년 1월 3일
편집: Stephen23 2018년 1월 3일
I have a comma-separated text file I am reading in and parsing using textscan. Two of the fields are the date and time of day. I am able to convert both fields to fractional days using datenum, with the intention to sum the two resulting vectors. The time field is formatted as HHMMSS.SS and the date field as ddmmyy.
My problem is that every so often one of the data messages includes the TIME field but not the DATE field. This is read in by textscan as an empty string. I have found that when datenum encounters the empty string, it returns an empty matrix rather than a NaN value or other filler value. This results in having vectors for TIME and DATE that are not the same length, and no obvious indicator of how to align the data.
How can I handle these empty strings in such a way that preserves the order of the data? Is there a way to get datenum to output a null value rather than simply ignoring the field? I would be fine with having a NaN or 0 or similar value to indicate the empty string. I would prefer to keep this vectorized if possible, but I understand a for loop may be necessary.
I'm using MATLAB 2016a.
  댓글 수: 2
Guillaume
Guillaume 2018년 1월 3일
Which version of matlab are you using? Is there any reason you're not using readtable and datetime which may make all of this easier?
Can you provide a sample of a file?
David K
David K 2018년 1월 3일
I'm using R2106a.
I'm not very familiar with readtable, but it doesn't appear to work for my files, as it's not simple columns of data. The first word in each line is a message ID which defines the number of and definition of the remaining fields. I use textscan to read in the entire file and then do a strcmp on the first word to grab all rows of a specific message type.
I use datenum rather than datetime mainly because I'm more familiar with it, particularly when it comes to lots of mathematical analysis of my data.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 1월 3일
편집: Stephen23 2018년 1월 3일
Just avoid passing them to datenum:
>> C = {'1988-06-03';'';'2018-03-03'};
>> idx = ~cellfun('isempty',C);
>> out = ~idx * NaN;
>> out(idx) = datenum(C(idx),'yyyy-mm-dd')
out =
726257
NaN
737122

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by