Function File: nlfilter (A, block_size, func)
Function File: nlfilter (A, block_size, func, …)
Function File: nlfilter (A, "indexed", …)

Process matrix in sliding blocks with user-supplied function.

Executes the function fun on each sliding block of size block_size, taken from the matrix A. Both the matrix A, and the block can have any number of dimensions. This function is specially useful to perform sliding/moving window functions such as moving average.

The output will have the same dimensions A, each one of its values corresponding to the processing of a block centered at the same coordinates in A, with A being padded with zeros for the borders (see below for indexed images). In case any side of the block is of even length, the center is considered at indices floor ([block_size/2] + 1).

The argument func must be a function handle that takes matrices of size block_size as input and returns a single scalar. Any extra input arguments to nlfilter are passed to func after the block matrix.

If A is an indexed image, the second argument should be the string "indexed" so that any required padding is done correctly as done by im2col.

Note: if func is a column compression function, i.e., it acts along a column to return a single value, consider using colfilt which usually performs faster. If func makes use of the colon operator to select all elements in the block, e.g., if func looks anything like @(x) sum (x(:)), it is a good indication that colfilt should be used. In addition, many sliding block operations have their own specific implementations (see help text of colfilt for a list).

See also: blockproc, col2im, colfilt, im2col.

Demonstration 1

The following code

 ## creates a "wide" diagonal (although it can be performed more
 ## efficiently with "imdilate (A, true (3))")
 nlfilter (eye (10), [3 3], @(x) any (x(:) > 0))

Produces the following output

ans =

  1  1  1  0  0  0  0  0  0  0
  1  1  1  1  0  0  0  0  0  0
  1  1  1  1  1  0  0  0  0  0
  0  1  1  1  1  1  0  0  0  0
  0  0  1  1  1  1  1  0  0  0
  0  0  0  1  1  1  1  1  0  0
  0  0  0  0  1  1  1  1  1  0
  0  0  0  0  0  1  1  1  1  1
  0  0  0  0  0  0  1  1  1  1
  0  0  0  0  0  0  0  1  1  1

Package: image