Get datenum to return missing instead of throwing an error
9 ビュー (過去 30 日間)
古いコメントを表示
Adithya Raajkumar
2022 年 5 月 11 日
コメント済み: Adithya Raajkumar
2022 年 5 月 11 日
Hello,
I normally program in R, so apologies if this question doesn't make sense or I missed an easy answer. I am using datenum to read a vector of character dates from a text file, which occassionally contains strings such as "NA" or "NaN". When this happens, datenum quits and throws an error, but I want datenum to return <missing> and keep going. This happens when I try datenum(NaN) in the console, but not when applying datenum to a character vector.
I don't want to pre-process the data by stripping out the "NA" strings, as that seems inelegant. I want Matlab to (possibly with a warning) return a missing value if it can't parse the date, rather than signal an error (this is how most date functions in R behave). How can I do this? I think the answer lies in try-catch, but I am not sure of the specifics of Matlab error handling.
3 件のコメント
採用された回答
Cris LaPierre
2022 年 5 月 11 日
5 件のコメント
Cris LaPierre
2022 年 5 月 11 日
編集済み: Cris LaPierre
2022 年 5 月 11 日
% imported elapsed days
d = 1:5;
% Add to base date
d0 = datetime(1970,1,1);
D = d0 + caldays(d)
その他の回答 (1 件)
Steven Lord
2022 年 5 月 11 日
As @Cris LaPierre said, we recommend using datetime instead of datenum. Let's create some example data.
t = string(datetime('today') + days([1; -2; 5; -17; 3]))
Change one of the entries so it's no longer valid date data or its format doesn't match the format of the rest of the data.
t(3, :) = 'invalid date';
t(5, :) = "December 25, 2022"
When we convert that to a datetime array the invalid data becomes a NaT (for Not-a-Time.)
dt = datetime(t)
You can detect which entries were not converted using ismissing or isnat.
wasInvalid = ismissing(dt)
You could then potentially try to correct the problem (by converting those entries from the original array using a different InputFormat in a second datetime call, for example, or letting datetime try to deduce a different format.)
dt(5) = datetime(t(5))
参考
カテゴリ
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!