Finding out the mesh indices of randomly generated points

조회 수: 2 (최근 30일)
LH
LH 2024년 2월 7일
편집: LH 2024년 2월 7일
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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by