How to re-grid a matrix to a coarser resolution and assign the sum of values in the finer cells to the coarser?
18 次查看(过去 30 天)
显示 更早的评论
Hello,
I have a matrix of 4530*6000 and need to re-grid it with a factor of 12.245 which gives a matrix of 370*490 dimensions. What I need is to assign the sum of the values of each 12.245*12.245 cells which are population to each cell of the new matrix. Interp2 does the re-grinding, but interpolate the values of original matrix. I came up with writing a code, but thought there may be a function to help. Thanks for your ideas please?
JZ
0 个评论
采纳的回答
Matthew Heberger
2023-1-4
You can use the functions imresize() or interp2() to rescale a matrix of 2D gridded data and calculate the sums in the output, if you multiply the result by the correct factor. This makes sense when you think of the output cells as containing the average value of the input cells. In order to convert the average to the sum, you have to multiply by the number of observations that were used to calculate the average.
Simple example:
% Create an 8 x 8 grid where every cell contains the value 1
A = ones(8);
sum(A, 'all')
% resize the matrix, making each dimension smaller by a factor of 4.
% Each cell in the output will be equivalent to 4 x 4 input cells, so scale up by a factor of 16.
A_upscaled = imresize(A, 1/4, 'bilinear') * 16;
sum(A_upscaled, 'all')
Example with data in the format of the original poster:
%% Create a grid with the same dimensions as OP, assign values using the famous peaks function
x = 0:1/5999:1;
y = 0:1/4529:1;
[X, Y] = meshgrid(x, y);
Z = peaks(X, Y);
% Plot the orginal grid and the new upscaled grid
figure
subplot(1, 2, 1)
imagesc(Z)
colorbar
title(sprintf("4530 x 6000 grid \n SUM = %e", sum(Z, "all") ))
% Resize the grid, and multiply all values by the square of the scale factor
scale_factor = 12.245;
Z2 = imresize(Z, 1/scale_factor, "bilinear") * scale_factor^2;
subplot(1, 2, 2);
imagesc(Z2)
colorbar;
title(sprintf("370 x 490 grid \n SUM = %e", sum(Z2, "all") ))
% The sums are approximately equal... errors due to floating point math and rounding
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!