Question

How do I create a dates series that gives me only the end of the month days? i.e.

31/01/1993
28/02/1993
...
31/01/2013
Was it helpful?

Solution 2

Use calendar function:

for year = 1993:2013
    for month = 1:12
        lastday = max(max(calendar(year,month)));
        fprintf('%02d/%02d/%04d\n',lastday,month,year)
    end
end

You can of course store result in matrix (or cell array) by changing fprintf with sprintf:

dates = char(zeros(12*21,10));
idx = 0;
for year = 1993:2013
    for month = 1:12
        idx = idx + 1;
        lastday = max(max(calendar(year,month)));
        dates(idx,:) = sprintf('%02d/%02d/%04d',lastday,month,year);
    end
end

---EDIT---

I've found thath there is aslo eomday function. So instead of line:

lastday = max(max(calendar(year,month)));

You can use:

lastday = eomday(year,month);

To see the algorithm of eomday function type in MATLAB:

open eomday

OTHER TIPS

The easy way would be to use the start of month days and subtract one. So, for instance:

datevec(datenum(1993,2,1)-1);

This would give you 1993 01 31. It is fairly simple to then do the same for each following month. e.g.

datenum(1993,2:13,1)-1;

would give you the end of month days for the whole of 1993.

EDIT:

As Luis pointed out, if you want the dates as formatted strings, as in the original question, you would use datestr:

% The '24' causes datestr to use a predefined format of the form 'dd/mm/yyyy'
datestr(datenum(1993,2:13,1)-1,24)

EDIT2:

To do multiple years, you can just increase the number of months. MATLAB's datenum function is clever - if you give it a date datenum(1993,14,1) it will return 1994/2/1, so if you wanted every month from 1993-2013 (20 years, so 240 months) you would use

datestr(datenum(1993,2:241,1)-1,24)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top