MATLAB Answers

Averaging scattered data over an n by n grid

5 views (last 30 days)
Menno van Dam
Menno van Dam on 23 Jul 2021
Commented: Menno van Dam on 23 Jul 2021
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 Comment
dpb on 23 Jul 2021
See histcounts2 with the output arguments of
Then average heights(ix,iy) for each pair ix, iy

Sign in to comment.

Accepted Answer

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.
%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 Comment
Menno van Dam
Menno van Dam on 23 Jul 2021
Thank you very much for writing it all out for me. It is exactly what I need.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by