I was trying to sort a series of polar coordinates by compass direction: everything in the N sector, then NNE, NE, ENE, E, … This is trickier than it looks, since the North sector includes angles between 348.75° and 11.25°.

It’s easier to think of the problem instead of being one of *N* bins centred on 0°, but rather one of *2N* bins starting at 0°. Then, all one needs to do is shift everything round by one of these half bins (so +1, modulo *2N*), then divide the number of bins back to the number we want. Done!

Here’s some code to do it. It may look like C-like pseudocode, but it’s real live AWK:

function bin(angle,nbins){ return int(((int(angle/(360.0/(nbins*2)))+1)%(nbins*2))/2); }

You probably want the angles to be between 0..360°. But you knew that.

## One reply on “binning by angle”

There’s a very spiffy little excel function described by David Jamieson here:

http://sandaysoft.com/forum/viewtopic.php?f=11&t=2479

that converts to cardinal directions. Here it is, in case the forum link goes away:-

=CHOOSE(INT(MOD(((cell *100) +1125),36000)/2250)+1,”N”, “NNE”, “NE”, “ENE”, “E”,”ESE”, “SE”, “SSE”, “S”, “SSW”, “SW”, “WSW”, “W”, “WNW”, “NW”, “NNW”)