Mariska
Mariska

Reputation: 1953

Matlab: Finding index of first char occurrence in Cell Array

I have a cell array of dates in MATLAB as such:

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

and I would like to extract the months only so that it returns

months = 
'10'
'9'

I tried this but it doesn't work:

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

It says "Error: ()-indexing must appear last in an index expression." Basically I have the (1) indexing there to get the index of the first occurrence of '/', and then I subtract 1 from it. Any ideas?

Upvotes: 2

Views: 454

Answers (2)

Divakar
Divakar

Reputation: 221564

Approach #1 Using 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)))

Code run -

dates = 
    '10/2/2010'
    '9/1/2011'
datevec_out =
        2010          10           2           0           0           0
        2011           9           1           0           0           0
out = 
    '10'
    ' 9'

Approach #2 By splitting into cells with 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)

Code run -

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'

Upvotes: 2

Autonomous
Autonomous

Reputation: 9075

A small modification will make your code work.

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

The hard-coded 1:3 should work even if you write the same date in 4 different styles.

1. 09/01/2011     2. 9/01/2011
3. 9/1/2011       4. 09/1/2011

The key here is to not encounter the second / sign.

Upvotes: 3

Related Questions