Clear Filters
Clear Filters

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

13 views (last 30 days)
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

Accepted Answer

Matthew Heberger
Matthew Heberger on 4 Jan 2023
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

More Answers (1)

Image Analyst
Image Analyst on 18 Jul 2016
Why not just use imresize()
newM = imresize(M, [370,490]);
  1 Comment
Jamal
Jamal on 19 Jul 2016
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

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!