function R = submreduce(A,r,c,fp)
% SUBMREDUCE Apply a specified function to convert submatrices into scalars
% Y = SUBMREDUCE(X,R,C,F) treats the 2D matrix X as consisting of
% submatrices of RxC rows and columns, and returns a smaller
% matrix with one value derived from each of these submatrices.
% That value is obtained by applying the function pointed to by F
% to a matrix where the all the submatrix values have been
% arranged in columns - i.e. the standard syntax for functions
% such as MIN() and SUM().
%
% Example: if X = [1 2 3 4 then SUBMREDUCE(X,2,2,@sum) = [14 22]
% 5 6 7 8]
%
% 2007-09-01 Dan Ellis dpwe@ee.columbia.edu
[nr,nc] = size(A);
if rem(nr,r) ~= 0 || rem(nc,c) ~= 0
msg = ['Cannot subdivide ',num2str(nr),'x',num2str(nc), ...
' into blocks of ', num2str(r),'x',num2str(c)];
error('maxreduce:mismatch',msg);
end
% Put it into a 4D array, flip the middle two dimensions, back to 2D
A = reshape(permute(reshape(A,r,nr/r,c,nc/c),[1 3 2 4]), r*c, nr*nc/r/c);
% Apply the actual operation (on cols)
R = feval(fp,A);
% Reshape to correct output
R = reshape(R,nr/r,nc/c);