Skip to content

MATLAB - Filter Function

The filter function is a fundamental tool in MATLAB for digital signal processing (DSP). It allows you to implement one-dimensional (1-D) digital filters, which are essential for tasks like noise reduction, signal smoothing, audio equalization, and analyzing financial time-series data. This tutorial will guide you through modern techniques for applying these filters effectively.

The primary syntax y = filter(b, a, x) applies a digital filter to the input data x. The filter is defined by a rational transfer function with numerator coefficients b and denominator coefficients a.

  • b: A vector of numerator coefficients. These define the “zeros” of the filter, corresponding to a Finite Impulse Response (FIR) component.
  • a: A vector of denominator coefficients. These define the “poles” of the filter, corresponding to an Infinite Impulse Response (IIR) component. For a simple FIR filter, a is just 1.
  • x: The input signal, which can be a vector or a matrix. If x is a matrix, filter processes each column independently by default.

The function can also handle initial conditions and operate along different dimensions, providing greater flexibility for complex applications: y = filter(b, a, x, zi, dim)

Let’s explore how to use filter with modern MATLAB practices.

Example 1: Smoothing a Signal with a Moving-Average (FIR) Filter

Section titled “Example 1: Smoothing a Signal with a Moving-Average (FIR) Filter”

A moving-average filter is one of the simplest FIR filters used for smoothing out short-term fluctuations to reveal longer-term trends. It works by replacing each data point with the average of its neighboring data points.

% For reproducibility, set the random number generator seed
rng('default');
% 1. Define Filter Coefficients for a 5-point moving average
windowSize = 5;
b = (1/windowSize) * ones(1, windowSize);
a = 1; % This makes it an FIR filter
% 2. Generate a Noisy Signal
t = 0:0.1:20; % Time vector
originalSignal = sin(t);
noise = 0.4 * randn(size(t));
x = originalSignal + noise; % Noisy input signal
% 3. Apply the Filter
y = filter(b, a, x);
% 4. Visualize the Results using tiledlayout for modern plotting
figure;
tiledlayout(2, 1);
% Top plot: Original noisy signal
nexttile;
plot(t, x, 'Color', [0 0.4470 0.7410]);
title('Original Noisy Signal');
xlabel('Time');
ylabel('Amplitude');
grid on;
% Bottom plot: Filtered signal
nexttile;
plot(t, y, 'Color', [0.8500 0.3250 0.0980], 'LineWidth', 1.5);
title('Filtered Signal (5-Point Moving Average)');
xlabel('Time');
ylabel('Amplitude');
grid on;
% Note: Observe the delay in the filtered signal, a characteristic of causal filters.

Example 2: Applying a Recursive (IIR) Filter to Matrix Data

Section titled “Example 2: Applying a Recursive (IIR) Filter to Matrix Data”

IIR filters are recursive, meaning the current output depends on both past inputs and past outputs. They are computationally efficient but require careful design to ensure stability. Here, we’ll apply a simple low-pass IIR filter to several signals stored in a matrix.

% For reproducibility
rng('default');
% 1. Define IIR Filter Coefficients (a simple low-pass filter)
b = 1;
a = [1, -0.9]; % A pole at z=0.9, making it recursive (IIR)
% 2. Generate a Matrix of Random Step Signals
numSignals = 3;
signalLength = 100;
x = rand(signalLength, numSignals) + (1:numSignals); % Create 3 distinct signals
% 3. Apply the Filter Along Columns (default behavior)
y = filter(b, a, x);
% 4. Visualize the First Signal for Comparison
figure;
t = 1:signalLength;
plot(t, x(:, 1), 'DisplayName', 'Input Data');
hold on;
plot(t, y(:, 1), 'LineWidth', 2, 'DisplayName', 'Filtered Data');
hold off;
legend;
title('IIR Filtering on the First Signal');
xlabel('Sample Index');
ylabel('Value');
grid on;

Instead of manually defining coefficients, the modern approach is to use MATLAB’s design functions. The designfilt function is highly recommended for its flexibility and readability.

% Modern filter design example for a low-pass FIR filter
Fs = 1000; % Sampling frequency
d = designfilt('lowpassfir', 'FilterOrder', 20, 'CutoffFrequency', 150, 'SampleRate', Fs);
% To get coefficients for use with filter():
% [b, a] = tf(d);
% For a more direct and often better approach, use the designed filter directly:
% filtered_signal = filter(d, input_signal);

For interactive design, the Filter Designer app (filterDesigner) provides a powerful graphical interface to design, analyze, and export filters.

Causal filters introduce a time delay. For applications where this is unacceptable, you can use zero-phase filtering with the filtfilt function. It processes the signal in both forward and reverse directions to cancel out any phase distortion.

% y_zero_phase = filtfilt(b, a, x);

The start of a filtered signal often contains transients. The filter function can accept initial conditions zi to mitigate this, which is crucial for processing data in chunks.

  • IIR Filter Instability: If an IIR filter’s output grows infinitely, it is unstable. This happens if the poles (roots of a) lie on or outside the unit circle. You can check this with isstable(b, a) or by visualizing poles with zplane(b, a).
  • Incorrect Coefficient Order: Ensure the b (numerator) and a (denominator) vectors are in the correct order in the filter function call.
  • Forgetting Normalization: For filters like the moving average, ensure the coefficients sum to 1 (sum(b)) if you want to preserve the signal’s overall gain.