【问题标题】:Matlab: Finding index of first char occurrence in Cell ArrayMatlab:查找单元格数组中第一个字符出现的索引
【发布时间】:2015-05-27 02:30:18
【问题描述】:

我在 MATLAB 中有一个日期元胞数组:

dates = {'10/2/2010' ; '9/1/2011'}

我只想提取月份以便它返回

months = 
'10'
'9'

我试过了,但它不起作用:

cellfun(@(x) x(1:(strfind(x,'/')(1)-1)), dates, 'UniformOutput', false)

它说“错误:()-索引必须出现在索引的最后 表达式。”基本上我有 (1) 索引来获取第一次出现 '/' 的索引,然后我从中减去 1。有什么想法吗?

【问题讨论】:

    标签: arrays matlab


    【解决方案1】:

    方法#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'
    

    【讨论】:

      【解决方案2】:

      一个小的修改将使您的代码工作。

      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
      

      这里的关键是不要遇到第二个/ 符号。

      【讨论】:

      • 这是另一个单行代码:cellfun(@(x) x, regexp(dates, '^\d+', 'match')),尽管我发现 Divakar 的方法更优雅,因为意图更清晰。
      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 2011-05-29
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      相关资源
      最近更新 更多