1## Copyright (C) 2008, 2009 Soren Hauberg
3## This file is part of Octave.
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.
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.
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/>.
20## @deftypefn {Function File} {@var{c} =} convn (@var{a}, @var{b}, @var{shape})
21## @math{N}-dimensional convolution of matrices @var{a} and @var{b}.
23## The size of the output is determined by the @var{shape} argument.
24## This can be any of the following character strings:
28## The full convolution result is returned. The size out of the output is
29## @code{size (@var{a}) + size (@var{b})-1}. This is the default behavior.
31## The central part of the convolution result is returned. The size out of the
32## output is the same as @var{a}.
34## The valid part of the convolution is returned. The size of the result is
35## @code{max (size (@var{a}) - size (@var{b})+1, 0)}.
38## @seealso{conv, conv2}
41function c = convn (a, b, shape = "full")
44 error ("convn: not enough input arguments");
47 if (!ismatrix (a) || !ismatrix (b) || ndims (a) != ndims (b))
48 error ("convn: first and second arguments must be matrices of the same dimensionality");
52 error ("convn: third input argument must be a string");
55 if (!any (strcmpi (shape, {"full", "same", "valid"})))
56 error ("convn: invalid shape argument: '%s'", shape);
59 ## Should we swap 'a' and 'b'?
60 ## FIXME -- should we also swap in any of the non-full cases?
61 if (numel (b) > numel (a) && strcmpi (shape, "full"))
68 switch (lower (shape))
70 a = pad (a, size (b)-1, size (b)-1);
72 a = pad (a, floor ((size (b)-1)/2), ceil ((size (b)-1)/2));
75 ## Perform convolution.
80## Helper function that performs the padding.
81function a = pad (a, left, right)
87 a = cat (dim, zeros (l, cl), a, zeros (r, cl));
95%! c2 = conv2 (a, b, "full");
96%! cn = convn (a, b, "full");
97%! assert (max (abs (cn(:)-c2(:))), 0, 100*eps);
100%! ## Compare to conv2
103%! c2 = conv2 (a, b, "same");
104%! cn = convn (a, b, "same");
105%! assert (max (abs (cn(:)-c2(:))), 0, 100*eps);
108%! ## Compare to conv2
111%! c2 = conv2 (a, b, "valid");
112%! cn = convn (a, b, "valid");
113%! assert (max (abs (cn(:)-c2(:))), 0, 100*eps);
117%! a = ones (10,10,10);
119%! c = convn (a, b, "valid");
120%! assert (all (c == numel (b)));
124%! a = complex(ones (10,10,10), ones(10,10,10));
125%! b = complex(ones (3,3,3), ones(3,3,3));
126%! c = convn (a, b, "valid");
127%! assert (all (c == 2*i*numel (b)));