0

I'm sure this is basic, but I can't come up to an easy way to reduce a matrix of population count by grid cell by adding up all the elements of the "small" cells which would fit in the new ones.

My matrix is 720x360 and would like to change it to 360x180. I thought about using imresize with 0.5 scale, and then assume the value per new grid is 4 times the old one.

I fell uneasy doing so though, as I can't find examples of similar cases. It'll be nice to have "sum" or "average" as an "interpolation" option or something like that.

Thanks in advance for any help

Cheers

Maria

  • So you want to sum over 2x2 blocks? Do you have the Image Processing Toolbox? Check `blockproc` or `im2col` – Luis Mendo May 25 '16 at 17:04
  • `conv2` with a 2x2 kernel and taking odd rows/columns would also work. – beaker May 25 '16 at 17:11
  • blockproc worked perfectly, thank you! it takes a bit longer than imresize but it works good for this case. I used the function `fun=@(block_struct)nansum(nansum(block_struct.data,1),2);` with blockproc specifying my cell side as [2 2], in case it helps anyone else ;-). Thanks a lot – user4004132 May 25 '16 at 17:23
  • Also note that bilinear interpolation **for a scale factor of 0.5** is equivalent to taking the average of the 2x2 neighborhood. – beaker May 25 '16 at 17:29
  • Thank you both, you saved my day. Sometimes you just get blocked with these things and I've been searching for some hours trying to avoid being silly in front of you ;-). Have a great day! – user4004132 May 25 '16 at 17:30
  • Actually I did imresize and multiplied by 4 but the results weren't the same as the sum I did by hand. It was pretty close, but still different. As they're big numbers there might be a roundup that changed the outcome I guess. Thanks again :-) – user4004132 May 25 '16 at 17:33

1 Answers1

0

If you have the Image Processing Toolbox:

x = randi(10,6,8); % example matrix
bs = [2 2]; % block size
y = col2im(sum(im2col(x, bs, 'distinct'), 1), [1 1], size(x)./bs, 'distinct');

How this works:

im2col(... 'distinct') arranges each distinct block of the given size into a column. sum(...,1) then sums each column. Finally, im2col(..., 'distinct') arranges the results back into a matrix of reduced size.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147