1 ## Copyright (C) 2006-2012 Alexander Barth
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{y1}, @var{y2}, @dots{}, @var{y}n] =} ndgrid (@var{x1}, @var{x2}, @dots{}, @var{x}n)
21 ## @deftypefnx {Function File} {[@var{y1}, @var{y2}, @dots{}, @var{y}n] =} ndgrid (@var{x})
22 ## Given n vectors @var{x1}, @dots{} @var{x}n, @code{ndgrid} returns
23 ## n arrays of dimension n. The elements of the i-th output argument
24 ## contains the elements of the vector @var{x}i repeated over all
25 ## dimensions different from the i-th dimension. Calling ndgrid with
26 ## only one input argument @var{x} is equivalent of calling ndgrid with
27 ## all n input arguments equal to @var{x}:
29 ## [@var{y1}, @var{y2}, @dots{}, @var{y}n] = ndgrid (@var{x}, @dots{}, @var{x})
33 ## Author: Alexander Barth <abarth@marine.usf.edu>
35 function varargout = ndgrid (varargin)
38 n = max ([nargout, 2]);
39 ## If only one input argument is given, repeat it n-times
40 varargin(1:n) = varargin(1);
41 elseif (nargin >= nargout)
42 n = max ([nargin, 2]);
44 error ("ndgrid: wrong number of input arguments");
47 ## Determine the size of the output arguments
52 if (! isvector (varargin{i}))
53 error ("ndgrid: arguments must be vectors");
56 shape(i) = length (varargin{i});
68 varargout{i} = repmat (reshape (varargin{i}, r), s);
77 %! [XX, YY, ZZ] = ndgrid (x, y, z);
78 %! assert (size_equal (XX, YY, ZZ));
79 %! assert (ndims (XX), 3);
80 %! assert (size (XX), [2, 3, 4]);
81 %! assert (XX(1) * YY(1) * ZZ(1), x(1) * y(1) * z(1));
82 %! assert (XX(end) * YY(end) * ZZ(end), x(end) * y(end) * z(end));
87 %! [XX1, YY1] = meshgrid (x, y);
88 %! [XX2, YY2] = ndgrid (x, y);
89 %! assert (size_equal (XX1, YY1));
90 %! assert (size_equal (XX2, YY2));
91 %! assert (ndims (XX1), 2);
92 %! assert (size (XX1), [3, 2]);
93 %! assert (size (XX2), [2, 3]);
94 %! assert (XX2(1) * YY2(1), x(1) * y(1));
95 %! assert (XX2(end) * YY2(end), x(end) * y(end));
96 %! assert (XX1, XX2.');
97 %! assert (YY1, YY2.');