Execute a function on a sliding 2D window over a matrix
Updated 24 Feb 2014

View License

OUT = blockfun( DATA, BLOCK, FUN )
OUT = blockfun( DATA, BLOCK, FUN, 'Name', Value, ... )
OUT = blockfun( DATA, BLOCK, FUN ) returns a matrix OUT of dimensions
size(DATA), where each element corresponds to the value obtained by
exectuing FUN on the values within a 2D window defined by BLOCK centered
at each element in DATA.
BLOCK can be a user defined binary matrix, used as a mask centered at
each position to identify the elements passed to FUN. Or BLOCK can be a
1- or 2-element vector indicating the dimensions of the 2D window.
FUN is a function handle.

OUT = blockfun( DATA, BLOCK, FUN, 'Name', Value, ... ) accepts additional
name-value pairs from the following list (defaults in {}):
'includeCenter' { true } - if false, the center value of the 2D window
is excluded from the input to FUN.
'padFunction' { @nan } - a function handle used to pad the matrix DATA
when the 2D window extends beyond the bounds of the matrix.
'positions' { 1 : numel(data) } - a vector containing the linear indices
at which to execute FUN. When specified, OUT is of the same size as the
position vector.
'maxPosLength' { 1e4 } - a scalar indicating the maximum number of
positions to evaluate at a time. If this value is too large, MATLAB may
experience out of memory errors.

Determine the underlying shape of a surface with noise
[xx, yy] = meshgrid((1:100) - 51);

surface = 2*xx + 0.4*yy + 0.2*xx.*yy;
imagesc(surface); axis square; axis off;

noisy = surface + randn(size(surface))*100;
imagesc(noisy); axis square; axis off;

recovered = blockfun( noisy, [6 6], @nanmedian );
imagesc(recovered); axis square; axis off;

Cite As

Gordon (2024). BLOCKFUN.M (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2013b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes

Bugfix correcting an error that occurs with small window sizes.

Added dependencies: default_param, get_params