]> Creatis software - CreaPhase.git/blob - octave_packages/m/general/nextpow2.m
update packages
[CreaPhase.git] / octave_packages / m / general / nextpow2.m
1 ## Copyright (C) 1995-2012 Kurt Hornik
2 ##
3 ## This file is part of Octave.
4 ##
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
9 ##
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ## General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING.  If not, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn {Function File} {} nextpow2 (@var{x})
21 ## If @var{x} is a scalar, return the first integer @var{n} such that
22 ## @tex
23 ## $2^n \ge |x|$.
24 ## @end tex
25 ## @ifnottex
26 ## 2^n @geq{} abs (x).
27 ## @end ifnottex
28 ##
29 ## If @var{x} is a vector, return @code{nextpow2 (length (@var{x}))}.
30 ## @seealso{pow2, log2}
31 ## @end deftypefn
32
33 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
34 ## Created: 7 October 1994
35 ## Adapted-By: jwe
36
37 function n = nextpow2 (x)
38
39   if (nargin != 1)
40     print_usage ();
41   endif
42
43   if (! (isscalar (x) || isvector (x)))
44     error ("nextpow2: X must be a scalar or a vector");
45   endif
46
47   t = length (x);
48   if (t > 1)
49     x = t;
50   endif
51
52   [f, n] = log2 (abs (x));
53   if (f == 0.5)
54     n = n - 1;
55   endif
56
57 endfunction
58
59 %!error nexpow2 ();
60 %!error nexpow2 (1, 2);
61
62 %!assert (nextpow2 (16), 4);
63 %!assert (nextpow2 (17), 5);
64 %!assert (nextpow2 (31), 5);
65 %!assert (nextpow2 (-16), 4);
66 %!assert (nextpow2 (-17), 5);
67 %!assert (nextpow2 (-31), 5);
68 %!assert (nextpow2 (1:17), 5);