MATLAB Answers

Averaging scattered data over an n by n grid

조회 수: 7(최근 30일)
Menno van Dam
Menno van Dam 2021년 7월 23일
댓글: Menno van Dam 2021년 7월 23일
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
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.
%simulate some data
L= x<=mean([xstart xend]) & y<=mean([ystart yend]) ;
%plot the distibution
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
% ^^
% 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);
  댓글 수: 1
Menno van Dam
Menno van Dam 2021년 7월 23일
Thank you very much for writing it all out for me. It is exactly what I need.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by