MATLAB Answers


How to repeatedly subdive vector rectangle into equal area?

Asked by a1
on 23 Jul 2019
Latest activity Commented on by a1
on 24 Jul 2019
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
box on
grid on
hold on
axis equal
% 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.


Sign in to comment.

1 Answer

Answer by Akira Agata
on 24 Jul 2019
Edited by Akira Agata
on 24 Jul 2019
 Accepted Answer

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);
hold on
h = histogram2(x,y,xEdges,yEdges,...
'DisplayStyle', 'tile',...
'FaceAlpha', 0.2);
for kk1 = 1:N
for kk2 = 1:M


@Akira Agata: the colors in the colorbar and the main axes are totally different. Is that intentional?
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...)
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.