Maddy
Maddy

Reputation: 2570

Subtract months from a given date in Matlab

I need to subtract 21 months from a given date.

My solution as given below only takes me to the first month of the given year :(

[a,b,c]= datevec(date);
b= b-21;
datestr(datenum(a,b,c)) %--> 11-Jan-2011 (WRONG).

I want the answer to be 11-June-2009.

Upvotes: 0

Views: 7529

Answers (1)

Gareth McCaughan
Gareth McCaughan

Reputation: 19971

Go via date numbers rather than date vectors and use addtodate:

>> d = datenum(date);
>> e = addtodate(d, -21, 'month');
>> datestr(e)

ans =

11-Jun-2009

Upvotes: 6

Related Questions