我在MATLAB中有一个日期单元格数组:
dates = {'10/2/2010' ; '9/1/2011'}
我想提取月份以便它返回
months =
'10'
'9'
我尝试了这个,但它不起作用:
cellfun(@(x) x(1:(strfind(x,'/')(1)-1)), dates, 'UniformOutput', false)
它说“错误:() - 索引必须出现在索引的最后 表达式。“基本上我有(1)索引来获取第一次出现'/'的索引,然后我从中减去1。任何想法?
答案 0 :(得分:3)
小修改将使您的代码正常工作。
cellfun(@(x) x(1:(strfind(x(1:3),'/')-1)), dates, 'UniformOutput', false)
即使您用4种不同的样式编写相同的日期,硬编码的1:3
也应该有效。
1. 09/01/2011 2. 9/01/2011
3. 9/1/2011 4. 09/1/2011
这里的关键是不要遇到第二个/
符号。
答案 1 :(得分:2)
方法#1 使用datevec
-
%// Input
dates = {'10/2/2010' ; '9/1/2011'}
%// Convert date and time to vector of components
datevec_out = datevec(dates)
%// Extract the month information only contained in the second column
out = cellstr(num2str(datevec_out(:,2)))
代码运行 -
dates =
'10/2/2010'
'9/1/2011'
datevec_out =
2010 10 2 0 0 0
2011 9 1 0 0 0
out =
'10'
' 9'
方法#2 通过分割为regexp(..'Split')
%// Input
dates = {'10/2/2010' ; '9/1/2011'}
%// Split into cells using `/` as the "separator"
dates_split = regexp(dates,'/','Split')
%// Vertically concatenate all cells into a single cell array
%// to reduce "cell-nesting"
dates_split_catcell = vertcat(dates_split{:})
%// Extract the month information only contained in the first column
out = dates_split_catcell(:,1)
代码运行 -
dates =
'10/2/2010'
'9/1/2011'
dates_split =
{1x3 cell}
{1x3 cell}
dates_split_catcell =
'10' '2' '2010'
'9' '1' '2011'
out =
'10'
'9'