]> Creatis software - CreaPhase.git/blob - octave_packages/audio-1.1.4/clip.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / audio-1.1.4 / clip.m
1 ## Copyright (C) 1999 Paul Kienzle
2 ##
3 ## This program is free software; you can redistribute it and/or modify
4 ## it under the terms of the GNU General Public License as published by
5 ## the Free Software Foundation; either version 2 of the License, or
6 ## (at your option) any later version.
7 ##
8 ## This program is distributed in the hope that it will be useful,
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 ## GNU General Public License for more details.
12 ##
13 ## You should have received a copy of the GNU General Public License
14 ## along with this program; If not, see <http://www.gnu.org/licenses/>.
15
16 ## Clip values outside the range to the value at the boundary of the
17 ## range.
18 ##
19 ## X = clip(X)
20 ##   Clip to range [0, 1]
21 ##
22 ## X = clip(X, hi)
23 ##   Clip to range [0, hi]
24 ##
25 ## X = clip(X, [lo, hi])
26 ##   Clip to range [lo, hi]
27
28 ## TODO: more clip modes, such as three level clip(X, [lo, mid, hi]), which
29 ## TODO: sends everything above hi to hi, below lo to lo and between to
30 ## TODO: mid; or infinite peak clipping, which sends everything above mid
31 ## TODO: to hi and below mid to lo.
32
33 function x = clip (x, range)
34
35   if (nargin == 2)
36     if (length(range) == 1)
37       range = [0, range];
38     end
39   elseif (nargin == 1)
40     range = [0, 1];
41   else
42     usage("X = clip(X [, range])");
43   end
44   try wfi = warning("query", "Octave:fortran-indexing").state;
45   catch wfi = "off";
46   end
47   unwind_protect
48     x (find (x > range (2))) = range (2);
49     x (find (x < range (1))) = range (1);
50   unwind_protect_cleanup
51     warning(wfi, "Octave:fortran-indexing");
52   end_unwind_protect
53
54 endfunction
55
56 %!error clip
57 %!error clip(1,2,3)
58 %!assert (clip(pi), 1)
59 %!assert (clip(-pi), 0)
60 %!assert (clip([-1.5, 0, 1.5], [-1, 1]), [-1, 0, 1]);
61 %!assert (clip([-1.5, 0, 1.5]', [-1, 1]'), [-1, 0, 1]');
62 %!assert (clip([-1.5, 1; 0, 1.5], [-1, 1]), [-1, 1; 0, 1]);
63 %!assert (isempty(clip([],1)));