MEDFILT

The median filter is a non-linear digital filtering technique, often used to remove noise from an image or signal. Such noise reduction is a typical pre-processing step to improve the results of later processing. Median filtering is very widely used in digital signal processing because, under certain conditions, it preserves edges while removing noise.

The main idea of the median filter is to run through the signal entry by entry, replacing each entry with the median of neighboring entries. The pattern of neighbors is called the “window”, which slides, entry by entry, over the entire signal.

Excel Usage

=MEDFILT(volume, kernel_size)
  • volume (list[list], required): Input array (Excel range).
  • kernel_size (int, optional, default: 3): Size of the median filter window (should be odd).

Returns (list[list]): The median filtered signal as a 2D array.

Example 1: Spike removal

Inputs:

volume kernel_size
1 2 100 4 5 3

Excel formula:

=MEDFILT({1,2,100,4,5}, 3)

Expected output:

Result
1 2 4 5 4
Example 2: Larger window

Inputs:

volume kernel_size
1 2 100 4 5 5

Excel formula:

=MEDFILT({1,2,100,4,5}, 5)

Expected output:

Result
1 2 4 4 4

Python Code

Show Code
import numpy as np
from scipy.signal import medfilt as scipy_medfilt

def medfilt(volume, kernel_size=3):
    """
    Perform a median filter on a signal array to remove spike noise.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.medfilt.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        volume (list[list]): Input array (Excel range).
        kernel_size (int, optional): Size of the median filter window (should be odd). Default is 3.

    Returns:
        list[list]: The median filtered signal as a 2D array.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        data = np.array(to2d(volume), dtype=float)
        kernel = int(kernel_size)

        if kernel <= 0 or kernel % 2 == 0:
            return "Error: kernel_size must be a positive odd integer"

        if data.ndim == 2 and data.shape[0] == 1:
            kernel_spec = [1, kernel]
        elif data.ndim == 2 and data.shape[1] == 1:
            kernel_spec = [kernel, 1]
        else:
            kernel_spec = kernel

        result = scipy_medfilt(data, kernel_size=kernel_spec)

        return result.tolist()
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

Input array (Excel range).
Size of the median filter window (should be odd).