将表字符串转换为datenum

时间:2017-07-31 09:34:10

标签: matlab datetime matlab-table

我有带字符串的Matlab表,我想将其转换为datenum格式。我试过了:

datenum(Tbl) 

但我收到了错误:

Error using datenum (line 181)
DATENUM failed.

Caused by:
    Error using datevec (line 103)
    The input to DATEVEC was not an array of character vectors.

以下是我的Tbl示例:

Tbl = table;
Tbl.('A') = {'29/07/2017'; 0};
Tbl.('B') = {'29/07/2017'; '31/07/2017'};

2 个答案:

答案 0 :(得分:2)

尝试varfun

varfun(@datenum,Tbl)

生产

datenum_A    datenum_B
_________    _________

12791        12791    
    0        13521    

选项2

或者,可以像这样一次完成一列:

Tbl.('A') = cellfun(@datenum,Tbl.('A'))

生产

Tbl =

  A           B      
_____    ____________

12791    '29/07/2017'
    0    '31/07/2017'

然后你可以为'B'等做这件事。

答案 1 :(得分:1)

首先转换table to an array,然后将datenum与日期格式一起应用。在数据中包含数字很奇怪,但无论如何,这是一个解决方案:

numdate= table2array(Tbl);       %Converting table to array
ind = cellfun(@ischar,numdate);  %Finding logical indices of dates stored as char array
%Finding serial date number of dates; not doing anything on numeric values
numdate(ind)=cellfun(@(x) datenum(x, 'dd/mm/yyyy'), numdate(ind),'un',0); %Serial Datenums
%Converting back the date number serials into dates    
dateback=numdate; dateback(ind)=cellfun(@datestr,numdate(ind),'un',0); 

<强>输出:

>> numdate

numdate =     
    [736905]    [736905]
    [     0]    [736907]

>> dateback

dateback =
    '29-Jul-2017'    '29-Jul-2017'
    [          0]    '31-Jul-2017'