Finding out the mesh indices of randomly generated points

5 次查看(过去 30 天)
Hi,
I want to find out where does each point from the randomly generated list belong in the pre-defined mesh grid of x and y. The grid is simple as shown on the left of the figure below. The red numbers are the indicies of each cell. The green values on the right are randomly geenrated and I want to find out the index of each point in that mesh.
The attempted code I have is as follows:
close all;
clear all;
%build the mesh area
%x axis
xmin = 0;
xmax = 2;
ndx = 4;
x = linspace(xmin,xmax,ndx+1);
%y axis
ymin = 0;
ymax = 1;
ndy = 2;
y = linspace(ymin,ymax,ndy+1);
%---------------
%Calculate the size of the mesh
N = ndx;
M = ndy;
NCells = N * M;
%---------------
%get the indices of each cell of the xy mesh
for i = 1:N %go through all x subdivisions
for j = 1:M %go throuhg all y subdivisions
%Index matrix of all cells in the mesh
MeshCellInd(i,j)= M*(i-1)+j;
end
end
%---------------
%define xy random points
%generate 10 random numbers on x on the interval [0 2]
% In general, you can generate N random numbers in the interval (a,b)
% with the formula r = a + (b-a).*rand(N,1).
X = 0 + (2-0).*rand(10,1);
%generate 10 random number on y on the interval [0 1]
Y = rand(10,1); %returns a random scalar drawn from the uniform distribution in the interval (0,1).
%concatenate random points on both axes
DATA = [X Y];
%---------------
%find out the index of each x,y randomly generated point
%---------------
Any help would be appreicted.
Thanks.

采纳的回答

LH
LH 2024-2-7
编辑:LH 2024-2-7
Thanks for your help and suggestions. I think I have solved this.
% Find out the cell index of each row on DATA
[~, ~, ~, bin_x, bin_y] =...
histcounts2(DATA(:,1), DATA(:,2), ...
x, y);
% Convert bin_x and bin_y IDs to cell ID
idx = M*(bin_x-1) + bin_y;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by