# Averaging scattered data over an n by n grid

11 views (last 30 days)
Menno van Dam on 23 Jul 2021
Commented: Menno van Dam on 23 Jul 2021
Hello,
I'm new to Matlab, and this is my first question here.
I'm working with a scattered dataset. I have a long array of height values, as well as two equally long arrays for the x and y coordinates per height value. So, point 1 has a height of z(1) and is located at x(1), y(1), and so forth. All xy values fall within a range of xstart:xend and ystart:yend.
I'd like to reduce the amount of values I have by taking the average over a smaller n by n grid. Since the data is scattered, it is possible no datapoints fall within a grid cell. In that case I'd like the cell value to be set to 0, instead of NaN. So the new arrays would be the average height per cell in a znew array, and the cell center coordinates in the xnew and ynew arrays. Just to be clear, I've illustrated what I want in the figure below:
What is the best way to do this? Thanks in advance.
##### 1 CommentShowHide None
dpb on 23 Jul 2021
See histcounts2 with the output arguments of
[~,~,~,ix,iy]=histcounts2(x,y,xEdges,yEdges);
Then average heights(ix,iy) for each pair ix, iy

Rik on 23 Jul 2021
Here is a full solution, using histcounts2 and accumarray to do the heavy lifting.
This solution plots in 3D, so you can verify with the example data that the locations of the text is correct.
xstart=0;xend=1;
ystart=0;yend=1;
n=2;
%simulate some data
N=50;
x=xstart+rand(N,1)*(xend-xstart);
y=ystart+rand(N,1)*(yend-ystart);
z=rand(N,1)+2*x-y*2;
L= x<=mean([xstart xend]) & y<=mean([ystart yend]) ;
x(L)=[];y(L)=[];z(L)=[];
%plot the distibution
plot3(x,y,z,'o')
hold on
plot([0.5 0.5 NaN 0 1],[0 1 NaN 0.5 0.5],'--k')
hold off
%determine the bin for the data
[~,~,~,ind_x,ind_y]=histcounts2(x,y,...
linspace(xstart,xend,n+1),...
linspace(ystart,yend,n+1));
% ^^
% don't forget +1, because these are the edges, not the number of bins
binned=accumarray([ind_x,ind_y],z,[n n],@mean,0);
text(0.25,0.25,sprintf('z=%.1f',binned(1,1)));
text(0.75,0.25,sprintf('z=%.1f',binned(2,1)));
text(0.25,0.75,sprintf('z=%.1f',binned(1,2)));
text(0.75,0.75,sprintf('z=%.1f',binned(2,2)));
view(-0.5,90)
##### 1 CommentShowHide None
Menno van Dam on 23 Jul 2021
Thank you very much for writing it all out for me. It is exactly what I need.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!