1 ## Copyright (C) 1994-2012 John W. Eaton
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} {} prepad (@var{x}, @var{l})
21 ## @deftypefnx {Function File} {} prepad (@var{x}, @var{l}, @var{c})
22 ## @deftypefnx {Function File} {} prepad (@var{x}, @var{l}, @var{c}, @var{dim})
23 ## Prepend the scalar value @var{c} to the vector @var{x} until it is of length
24 ## @var{l}. If @var{c} is not given, a value of 0 is used.
26 ## If @code{length (@var{x}) > @var{l}}, elements from the beginning of
27 ## @var{x} are removed until a vector of length @var{l} is obtained.
29 ## If @var{x} is a matrix, elements are prepended or removed from each row.
31 ## If the optional argument @var{dim} is given, operate along this
33 ## @seealso{postpad, cat, resize}
36 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
39 function y = prepad (x, l, c, dim)
41 if (nargin < 2 || nargin > 4)
45 if (nargin < 3 || isempty (c))
49 error ("prepad: third argument must be empty or a scalar");
56 ## Find the first non-singleton dimension.
57 (dim = find (sz > 1, 1)) || (dim = 1);
59 if (!(isscalar (dim) && dim == fix (dim))
60 || !(1 <= dim && dim <= nd))
61 error ("prepad: DIM must be an integer and a valid dimension");
65 if (! isscalar (l) || l < 0)
66 error ("prepad: second argument must be a positive scaler");
76 idx = repmat ({':'}, nd, 1);
81 y = cat (dim, c * ones (sz), x);
88 %!error prepad (1,2,3,4,5);
89 %!error prepad ([1,2], 2, 2,3);
91 %!assert (prepad ([1,2], 4), [0,0,1,2]);
92 %!assert (prepad ([1;2], 4), [0;0;1;2]);
94 %!assert (prepad ([1,2], 4, 2), [2,2,1,2]);
95 %!assert (prepad ([1;2], 4, 2), [2;2;1;2]);
97 %!assert (prepad ([1,2], 2, 2, 1), [2,2;1,2]);
99 ## FIXME -- we need tests for multidimensional arrays.