MATLAB: Produce bin averaged latitude and longitude grids

.binbin averaged gridgridlatitudelongitudematrix

I have a set of data with each row representing a series of observations taken at a particular point. Each column represents a different observation as well as information regarding where the data was collected (longitude and latitude (column 4 and 5 respectively). The data needs to be gridded so that the data is over 2.5degrees latitude 5.0degrees longitude bin-averaged grids. How would I go about doing this?

Best Answer

Assuming that longitudes are in the range [0,360[ and latitudes in the range ]-90,90[, here is part of a solution that you could fine tune. I assume that your data set is stored in numeric array data.
First, build longitude and latitude bin IDs, and an array of bin IDs matching lon/lat of columns 4/5 of your data set:
lon_binID = 1 + floor( data(:,4) ./ 5 ) ;
lat_binID = 37 + floor( data(:,5) ./ 2.5 ) ;
binID = [lon_binID, lat_binID] ;
nBin = 72 ; % # of bins per lon/lat.
For extensive data, compute the sum per bin as follows. Assume that column 3 is e.g. a mass of something..
sum_bin = accumarray( binID, data(:,3), [nBin, nBin] ) ;
Here sum_bin is a 72x72 array of sum per bin. It is slightly more complicated for intensive data, as in theory we would need a count of binned values to compute the mean (by division of sums by counts). Thankfully, ACCUMARRAY allows us to specify the accumulation function (default = @sum). Assume that column 2 of data is the temperature..
mean_bin = accumarray( binID, data(:,2), [nBin, nBin], @mean ) ;
What changed here is that we passed a handle for function MEAN to ACCUMARRAY. The @ operator returns a handle on/for the function which follows; it's a way to pass functions to other functions.
Note that ACCUMARRAY can be quite slow when used with a user defined accumulation function, or sometimes a count per bins is really needed. Here is a trick to get it: accumulating a vector of ones..
onesVector = ones( size(data,1), 1 ) ;
count_bin = accumarray( binID, onesVector, [nBin, nBin] ) ;
It would be easy to compute the mean temperature from there if we had to..
sum_bin = accumarray( binID, data(:,2), [nBin, nBin] ) ;
mean_bin = sum_bin ./ count_bin ;
Hope it helps!