]> Creatis software - CreaPhase.git/blob - octave_packages/m/general/polyarea.m
update packages
[CreaPhase.git] / octave_packages / m / general / polyarea.m
1 ## Copyright (C) 1999-2012 David M. Doolin
2 ##
3 ## This file is part of Octave.
4 ##
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.
9 ##
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.
14 ##
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/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn  {Function File} {} polyarea (@var{x}, @var{y})
21 ## @deftypefnx {Function File} {} polyarea (@var{x}, @var{y}, @var{dim})
22 ##
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.
28 ##
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}.
31 ##
32 ## @end deftypefn
33
34 ## todo:  Add moments for centroid, etc.
35 ##
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?).
40
41 ## Author: David M. Doolin <doolin@ce.berkeley.edu>
42 ## Date: 1999-04-14
43 ## Modified-by:
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
49
50 function a = polyarea (x, y, dim)
51   if (nargin != 2 && nargin != 3)
52     print_usage ();
53   elseif (size_equal (x, y))
54     if (nargin == 2)
55       a = abs (sum (x .* (shift (y, -1) - shift (y, 1)))) / 2;
56     else
57       a = abs (sum (x .* (shift (y, -1, dim) - shift (y, 1, dim)), dim)) / 2;
58     endif
59   else
60     error ("polyarea: X and Y must have the same shape");
61   endif
62 endfunction
63
64 %!shared x, y
65 %! x = [1;1;3;3;1];
66 %! y = [1;3;3;1;1];
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)