How to re-grid a matrix to a coarser resolution and assign the sum of values in the finer cells to the coarser?

16 次查看(过去 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

采纳的回答

Matthew Heberger
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')
ans = 64
% 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')
ans = 64
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

更多回答(1 个)

Image Analyst
Image Analyst 2016-7-18
Why not just use imresize()
newM = imresize(M, [370,490]);
  1 个评论
Jamal
Jamal 2016-7-19
Dear Image Analyst,
Thanks, but I need to sum up cell values and assign it to the coarser resolution. Apparently, imresize cannot do this!? Please also see the last comment on the answer by Stephen.
Thanks JZ

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by