Summing scattered data over a 2D grid

12 views (last 30 days)
I have three arrays of values: X-coordinate, Y-coordinate, and concentation. Each point in the image has its own unique concentration value assigned to it.
As you can see in the image, this data is irregularly scattered. However, I would like to be able to define a grid (like the one in the image), and sum the concentration values of all the points that lie within each grid and points that lie on the boundary of the grids. If a value is on the boundary of two grids, it does not matter which grid it is included in but it cannnot be included in the other grid, so no duplicates. As a check, I need the sum of the final gridded data to be the same as the sum of the concentration array.
I would imagine you could use histograms in some way, which I have seen on here for similar applications, but I need to actually sum the data within the bins, not count the number of occurences.

Accepted Answer

Torsten
Torsten on 12 Apr 2023
Edited: Torsten on 12 Apr 2023
format long
% Generate random coordinates and concentrations
n = 100000;
x = -0.5+rand(n,1);
y = -0.5+rand(n,1);
conc = 10*rand(n,1);
% Define the grid volumes and grid points
conc_dense = zeros(10,10);
x_dense = -0.5:0.1:0.5;
y_dense = -0.5:0.1:0.5;
% Check which coordinates belong to grid volume (i,j) and sum concentrations
% therein
for i = 1:9
for j = 1:9
idx = x >=x_dense(i) & x < x_dense(i+1) & y >=y_dense(j) & y < y_dense(j+1);
conc_dense(i,j) = sum(conc(idx));
end
end
for i = 10
for j = 1:9
idx = x >=x_dense(i) & x <= x_dense(i+1) & y >= y_dense(j) & y < y_dense(j+1);
conc_dense(i,j) = sum(conc(idx));
end
end
for i = 1:9
for j = 10
idx = x >=x_dense(i) & x < x_dense(i+1) & y >= y_dense(j) & y <= y_dense(j+1);
conc_dense(i,j) = sum(conc(idx));
end
end
for i = 10
for j = 10
idx = x >= x_dense(i) & x <= x_dense(i+1) & y >= y_dense(j) & y <= y_dense(j+1);
conc_dense(i,j) = sum(conc(idx));
end
end
% Check mass balance
sum(conc)
ans =
4.991108278257297e+05
sum(conc_dense(:))
ans =
4.991108278257297e+05

More Answers (0)

Community Treasure Hunt

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

Start Hunting!