Iulius Caesar
Iulius Caesar

Reputation: 83

eliminate chars from cell in matlab

I have a vector of all Dates from 2015, i.e.:

'01.01.2015'
'02.01.2015'
.
.
.
'31.12.2015'

How do I eliminate the days out of the list? so that the result is a list like this:

'01.2015'
'01.2015'
.
.
.
'12.2015'
'12.2015'

Thank you a lot! Additionally, it would be a great help first, if i knew, how to eliminate the days from one date. Thanks!

Upvotes: 0

Views: 65

Answers (2)

Benoit_11
Benoit_11

Reputation: 13945

Since all your strings are of the same format, you can select the characters starting from the 4th character in every string until the last character:

DatesCell = {'01.01.2015';'02.01.2015';'21.12.2015'}

NewDates = cellfun(@(x) x(4:end),DatesCell,'uni',0)

This code uses cellfun, which is only a for loop in disguise.

The following is equivalent:

DatesCell = {'01.01.2015';'02.01.2015';'21.12.2015'}

NewDatesLoop = cell(numel(DatesCell),1);
for k =1:numel(DatesCell)

    NewDatesLoop{k} = DatesCell{k}(4:end);

end

Output:

NewDates = 

    '01.2015'
    '01.2015'
    '12.2015'


NewDatesLoop = 

    '01.2015'
    '01.2015'
    '12.2015'

Upvotes: 2

sco1
sco1

Reputation: 12214

If your dates are always going to be in the same format you can do it with a simple cellfun call:

testdates = {'01.01.2015';'02.01.2015';'03.01.2015';'04.01.2015'};

myrange = [1:2 6:10];
newdates = cellfun(@(x) x(myrange), testdates, 'UniformOutput', false);

Which returns:

newdates = 

    '01.2015'
    '02.2015'
    '03.2015'
    '04.2015'

cellfun applies some function to each cell in a cell array. What I use it for here is to create a new array using the indices of myrange applied to each cell. Note that this is not a robust methodology and will break as soon as your date format changes.

For a more robust approach you could consider using datenum and datestr:

testdates = {'01.01.2015';'02.01.2015';'03.01.2015';'04.01.2015'};

serialdates = datenum(testdates, 'mm.dd.yyyy');
newdates = datestr(serialdates, 'mm.yyyy');

Which returns:

newdates =

01.2015
02.2015
03.2015
04.2015

This will also break if your date format changes (or varies across the array), but the behavior is more explicit than the cellfun call.

Upvotes: 1

Related Questions