# Averaging scattered data over an n by n grid

조회 수: 7(최근 30일)
Menno van Dam 2021년 7월 23일
댓글: Menno van Dam 2021년 7월 23일
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표시숨기기 없음
dpb 2021년 7월 23일
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 2021년 7월 23일
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표시숨기기 없음
Menno van Dam 2021년 7월 23일
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!

Translated by