]> Creatis software - CreaPhase.git/blob - octave_packages/financial-0.4.0/months.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / financial-0.4.0 / months.m
1 ## Copyright (C) 2008 Bill Denney <bill@denney.ws>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {mos =} months (startdate, enddate)
18 ## @deftypefnx {Function File} {mos =} months (startdate, enddate, endmonthflag)
19 ##
20 ## Return the number of whole months between @var{startdate} and
21 ## @var{enddate}.  @var{endmonthflag} defaults to 1.
22 ##
23 ## If @var{endmonthflag} is true, then if both the @var{startdate} and
24 ## the @var{enddate} are end of month dates and @var{enddate} has fewer
25 ## days in the month than @var{startdate}, @var{endmonthflag} = 1 treats
26 ## @var{enddate} as the end of a month, but @var{endmonthflag} = 0 does
27 ## not.
28 ##
29 ## @seealso{yeardays, yearfrac}
30 ## @end deftypefn
31
32 function mos = months (startdate, enddate, endmonthflag = 1)
33
34   if (nargin < 2 || nargin > 3)
35     print_usage ();
36   endif
37
38   s = datevec (startdate);
39   e = datevec (enddate);
40   s_eom = (s(:,3) == eomday(s(:,1), s(:,2)));
41   e_eom = (e(:,3) == eomday(e(:,1), e(:,2)));
42
43   ## Handle the end of the month correctly
44   dayadj = ((s(:,3) > e(:,3)) & endmonthflag & s_eom & e_eom);
45
46   mos = 12*(e(:,1) - s(:,1)) + (e(:,2) - s(:,2)) - (s(:,3) > e(:,3)) + dayadj;
47
48 endfunction
49
50 ## Tests
51 %!assert(months('may 31 2004', 'jun 30 2004'), 1)
52 %!assert(months({'may 31 2004' 'may 30 2004'}, 'jun 30 2004'), [1;1])
53 %!assert(months('may 31 2004', 'jun 30 2004', 1), 1)
54 %!assert(months({'may 31 2004' 'may 30 2004'}, 'jun 30 2004', 1), [1;1])
55 %!assert(months('may 31 2004', 'jun 30 2004', 0), 0)
56 %!assert(months({'may 31 2004' 'may 30 2004'}, 'jun 30 2004', 0), [0;1])
57 %!assert(months('jun 30 2005', 'june 30 2006'), 12)
58 %!assert(months('jun 30 2005', 'june 29 2006'), 11)