MATLAB: Collate Data in Grid

2ddatagridsummaryzonal statistics

N.B.) The center of the grid relates to (x,y) co-ordinate (0,0).

Best Answer

In addition to Image Analyst's hints, you could also look at
Alternatively, here is a short example which illustrates how to grid data "by hand" on a regular grid. It can be adapted to irregular grids, to produce what is sometimes named zonal statistics in GIS contexts.
R = 4 ;
% - Define dummy data.
n = 15 ;
x = -R + 2*R*rand( n, 1 ) ;
y = -R + 2*R*rand( n, 1 ) ;
v1 = randi( 20, n, 1 ) ; % A series of data associated with points.
v2 = randi( 20, n, 1 ) ; % Another series.
% - Build grid.
nBinsX = 3 ;
nBinsY = 2 ;
xg = linspace( -R, R, nBinsX+1 ) ;
yg = linspace( -R, R, nBinsY+1 ) ;
nCells = nBinsX * nBinsY ;
% - Build figure.
figure(1) ; clf ; hold on ;
set( gcf, 'Color', 'w', 'Units', 'Normalized', ...
'Position', [0.1,0.1,0.6,0.6] ) ;
% - Plot grid.
plot( [xg;xg], repmat( [-R;R], 1, numel( xg )), 'Color', 0.8*[1,1,1] ) ;
plot( repmat( [-R;R], 1, numel( yg )), [yg;yg], 'Color', 0.8*[1,1,1] ) ;
xlim( 1.5*[-R,R] ) ; ylim( 1.5*[-R,R] ) ;
% - Build set of unique IDs for cells.
xId = sum( bsxfun( @ge, x, xg(1:end-1) ), 2 ) ;
yId = sum( bsxfun( @ge, y, yg(1:end-1) ), 2 ) ;
cellId = nBinsY * (xId - 1) + yId ;
% - Plot cell IDs.
labels = arrayfun( @(k)sprintf( '%d', k ), 1:nCells, 'UniformOutput', false ) ;
[X,Y] = meshgrid( (xg(1:end-1)+xg(2:end))/2, (yg(1:end-1)+yg(2:end))/2 ) ;
text( X(:), Y(:), labels, 'Color', 'b', 'FontSize', 14 ) ;
% - Plot data points with labels.
plot( x, y, 'rx', 'LineWidth', 2, 'MarkerSize', 8 ) ;
labels = arrayfun( @(k)sprintf( 'P%d\\in%d | %d,%d', k, cellId(k), ...
v1(k), v2(k) ), 1:n, 'UniformOutput', false ) ;
text( x, y+R/100, labels, 'Color', 'k', 'FontSize', 9, ...
'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' ) ;
% - Compute some stat (sum, mean) per block on v1 and v2.
blockSum_v1 = accumarray( cellId, v1, [nCells, 1] ) ;
blockMean_v2 = accumarray( cellId, v2, [nCells, 1], @mean ) ;
fprintf( '\nBlock sum v1 =\n' ) ;
disp( blockSum_v1 ) ;
fprintf( '\nBlock mean v2 =\n' ) ;
disp( blockMean_v2 ) ;
This outputs
and
Block sum v1 =
25
58
9
24
28
28
Block mean v2 =
17.5000
10.0000
6.5000
7.5000
13.0000
11.5000
Note that if you eliminate all the "demo" code, the approach reduces to almost a one-liner for defining cellIDs and then a one-liner per stat.
Related Question