]> Creatis software - CreaPhase.git/blob - octave_packages/miscellaneous-1.1.0/clip.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / miscellaneous-1.1.0 / clip.m
1 ## Copyright (C) 1999 Paul Kienzle <pkienzle@users.sf.net>
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} {@var{x} =} clip (@var{x})
18 ## @deftypefnx {Function File} {@var{x} =} clip (@var{x}, @var{hi})
19 ## @deftypefnx {Function File} {@var{x} =} clip (@var{x}, [@var{lo}, @var{hi}])
20 ## Clip @var{x} values outside the range.to the value at the boundary of the
21 ## range.
22 ##
23 ## Range boundaries, @var{lo} and @var{hi}, default to 0 and 1 respectively.
24 ##
25 ## @var{x} = clip (@var{x})
26 ##   Clip to range [0, 1]
27 ##
28 ## @var{x} = clip (@var{x}, @var{hi})
29 ##   Clip to range [0, @var{hi}]
30 ##
31 ## @var{x} = clip (@var{x}, [@var{lo}, @var{hi}])
32 ##   Clip to range [@var{lo}, @var{hi}]
33 ## @end deftypefn
34
35 ## TODO: more clip modes, such as three level clip(X, [lo, mid, hi]), which
36 ## TODO: sends everything above hi to hi, below lo to lo and between to
37 ## TODO: mid; or infinite peak clipping, which sends everything above mid
38 ## TODO: to hi and below mid to lo.
39
40 function x = clip (x, range = [0, 1])
41
42   if (nargin < 1 || nargin > 2)
43     print_usage;
44   else
45     if (numel (range) == 2)
46       ## do nothing, it's good
47     elseif (numel (range) == 1)
48       range = [0, range];
49     else
50       print_usage;
51     endif
52   endif
53
54   x (x > range (2)) = range (2);
55   x (x < range (1)) = range (1);
56
57 endfunction
58
59 %!error clip
60 %!error clip(1,2,3)
61 %!assert (clip(pi), 1)
62 %!assert (clip(-pi), 0)
63 %!assert (clip([-1.5, 0, 1.5], [-1, 1]), [-1, 0, 1]);
64 %!assert (clip([-1.5, 0, 1.5]', [-1, 1]'), [-1, 0, 1]');
65 %!assert (clip([-1.5, 1; 0, 1.5], [-1, 1]), [-1, 1; 0, 1]);
66 %!assert (isempty(clip([],1)));