MATLAB: Summing within an array to change the size


I have an array that has dimensions of 111x46x2. I want to sum the values in the first 3×3 block to become the first value of the next matrix repeating this until the last column is summed together. The dimensions of the new matrix should be 37x16x2.
I could make the dimensions of the original matrix 111x48x2 if that makes the calculations easier and more efficient. The 9×9 blocks will have values only in certain locations such as [ 0 0 #; # 0 0; 0 # 0]; and the last column will have values in each row.

Best Answer

  • If you have the Image Processing Toolbox:
    x = rand(111,46,2);
    y = blockproc(x,[3 3],@(s)sum(sum(,1),2));
    Or if you don't:
    z = convn(x,ones(3),'valid');
    z = z(1:3:end,1:3:end,:); %may need to crop differently depending on last edges