I cannot resist. Writing the code rm -rf posted was one of my first Mathematica programming exercises from over teneleven years ago. (Boy, time flies.) Here's a copy of the old Notebook, which I kept, and yes, these are the actual notes I wrote myself. (I do not attest to their present accuracy, only their historical record.)
Polygon
Area of non-self-intersecting polygons, described by a set of {x,y} points, using the direct Determinant method. In this version, emphasis was placed on conciseness of code.
polyarea = Abs@Tr[Det /@ Partition[#, 2, 1, 1]]/2 &;Again, the Determinant method, but in a semi-explicit form that is somewhat more efficient.
polyarea = Abs[Tr[#*#4 - #2*#3 & @@@ Partition[Flatten[#], 4, 2, 1]]/2] &;These are compiled versions of the prior two functions, respectively. Of note is that the version using Det is only marginally improved with Compile, while the other becomes several times more efficient. Viewing the compiled code will show that Det is apparently not actually compiled (it is explicit). Also note the changes that were made to each function to conform to the constraints of Compile.
polyarea = Compile[{{v, _Real, 2}}, Abs@Tr[Det /@ Partition[Append[v, v[[1]]], 2, 1]]/2]; polyarea = Compile[{{v, _Real, 2}}, Abs[Tr[#[[1]]*#[[4]] - #[[2]]*#[[3]] & /@ Partition[Flatten[Append[v, v[[1]]]], 4, 2]]/2]];Updated May 26, 2002.
In this function the Determinant method is optimized using Dot-products.
polyarea = Block[{x, y, R = RotateLeft}, {x, y} = Thread@#; Abs[x.R@y - [email protected]]/2] &;This compiled version of the Dot-based function is nearly twice as efficient as the non-compiled version. Amazingly, this makes it over 30 times as fast as the direct Determinant approach.
polyarea = Compile[{{v, _Real, 2}}, Block[{x, y}, {x, y} = Transpose@v; Abs[x.RotateLeft@y - [email protected]]/2]];
By the way, my current code for thisthese days I would use Module. I for the non-compiled version; I used to abuse Block rather badly.