1 ## Copyright (C) 1999-2012 David M. Doolin
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} {} polyarea (@var{x}, @var{y})
21 ## @deftypefnx {Function File} {} polyarea (@var{x}, @var{y}, @var{dim})
23 ## Determine area of a polygon by triangle method. The variables
24 ## @var{x} and @var{y} define the vertex pairs, and must therefore have
25 ## the same shape. They can be either vectors or arrays. If they are
26 ## arrays then the columns of @var{x} and @var{y} are treated separately
27 ## and an area returned for each.
29 ## If the optional @var{dim} argument is given, then @code{polyarea}
30 ## works along this dimension of the arrays @var{x} and @var{y}.
34 ## todo: Add moments for centroid, etc.
36 ## bugs and limitations:
37 ## Probably ought to be an optional check to make sure that
38 ## traversing the vertices doesn't make any sides cross
39 ## (Is simple closed curve the technical definition of this?).
41 ## Author: David M. Doolin <doolin@ce.berkeley.edu>
44 ## 2000-01-15 Paul Kienzle <pkienzle@kienzle.powernet.co.uk>
45 ## * use matlab compatible interface
46 ## * return absolute value of area so traversal order doesn't matter
47 ## 2005-10-13 Torsten Finke
48 ## * optimization saving half the sums and multiplies
50 function a = polyarea (x, y, dim)
51 if (nargin != 2 && nargin != 3)
53 elseif (size_equal (x, y))
55 a = abs (sum (x .* (shift (y, -1) - shift (y, 1)))) / 2;
57 a = abs (sum (x .* (shift (y, -1, dim) - shift (y, 1, dim)), dim)) / 2;
60 error ("polyarea: X and Y must have the same shape");
67 %!assert (polyarea(x,y), 4, eps)
68 %!assert (polyarea([x,x],[y,y]), [4,4], eps)
69 %!assert (polyarea([x,x],[y,y],1), [4,4], eps)
70 %!assert (polyarea([x,x]',[y,y]',2), [4;4], eps)