How to repeatedly subdive vector rectangle into equal area?

1 view (last 30 days)
I have x,y point data that I am trying to analyze in "swaths" or rectangles along the x-axis. I need to take the rectangle and subdivide it into equal areas, and count the number of areas that contain points.
Consider this example with a very small x,y dataset:
% make dummy data
x = 10*rand(30,1);
y = 25*rand(30,1);
% set up basis for building swaths or rectangles
step = 1;
xmax = step*(ceil(max(x)/step)); % rounds up to nearest step size
centers = 0:step/2:xmax;
centers = centers';
ymax = step*(ceil(max(y)/step));
%% will ultimately loop over all centers, but just consider one for now
jj = 2;
xr = [centers(jj-1), centers(jj+1), centers(jj+1), centers(jj-1), centers(jj-1)];
yr = [ymax+step, ymax+step, 0-step, 0-step, ymax+step];
% plot for discussion
scatter(x,y,'.')
box on
grid on
hold on
axis equal
plot(xr,yr,'blue')
% this gives point counts inside big rectangle as a sanity check
% but I need to do this for all the equal areas that I need to build
[in,on] = inpolygon(x,y,xr,yr);
num_points_example = sum(in);
So in this example, my blue rectangle is 26x1 units. To make equal areas, I need to keep the x-axis length the same (=1) and break the rectangle down into 26 square along the y-axis. My question is, how do I programmatically build a grid or mesh for this 26x1? Note that in the next step, I'll be subdividing it further (52x2), etc., always maintaining equal area. I only have the basic Matlab, no fancy toolboxes, R2018a.

Accepted Answer

Akira Agata
Akira Agata on 24 Jul 2019
Edited: Akira Agata on 24 Jul 2019
How about using histogram2 function?
The following is an example.
% make dummy data
x = 10*rand(30,1);
y = 25*rand(30,1);
% min. and max. of x and y
xlim = [-2 12];
ylim = [-5 30];
% Number of rectangle units (N x M)
N = 12;
M = 2;
% Count (x,y) points in each unit
xEdges = linspace(xlim(1),xlim(2),N+1);
yEdges = linspace(ylim(1),ylim(2),M+1);
figure
scatter(x,y,'.')
hold on
h = histogram2(x,y,xEdges,yEdges,...
'DisplayStyle', 'tile',...
'ShowEmptyBins','on',...
'FaceAlpha', 0.2);
for kk1 = 1:N
for kk2 = 1:M
text(mean(xEdges(kk1:kk1+1)),mean(yEdges(kk2:kk2+1)),...
num2str(h.Values(kk1,kk2)),...
'FontSize',12)
end
end
colorbar
  3 Comments
Akira Agata
Akira Agata on 24 Jul 2019
Edited: Akira Agata on 24 Jul 2019
Thank you for your comment, and sorry for causing some confusion.
This is because 'FaceAlpha' option was set to 0.2 to clearly show both scattered data points and numbers.
To keep consistency, please delete 'FaceAlpha' option, and move scatter(x,y,'.') after histogram2 (but in that case, the plot would be non-user-friendly...)
newbie9
newbie9 on 24 Jul 2019
Oh wow, that is so clever @Akira Agata, thank you! I will give this a try and report back. Thanks so much for your time

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!