Skip to main content
v2026.11,858 entries · CC-BY 4.0

FIR MATLAB: Filter Design with fir1 and freqz

Design finite impulse response (FIR) filters in MATLAB with fir1 and designfilt. Learn coefficient calculation, linear-phase delay and zero-phase filtering.

Written and maintained by CASRAI Editorial Board

Last updated

In scientific computing and experimental data processing, designing a finite impulse response (FIR) filter in MATLAB allows researchers to remove unwanted spectral noise, isolate physiological rhythms, or separate measurement bands while maintaining strictly linear phase characteristics. Unlike infinite impulse response (IIR) filters, FIR filters are inherently stable and introduce a constant group delay across all frequencies, preserving the temporal waveform shape of transients such as event-related potentials or mechanical shock waves.

What it is used for in research

Finite impulse response filtering in MATLAB is standard across empirical disciplines requiring deterministic phase response and artifact suppression:

  • Electrophysiology and Neuroscience: Preprocessing electroencephalography (EEG) and local field potential recordings to remove electrical mains interference (50 Hz or 60 Hz line noise) without altering the latency of evoked wave peaks.
  • Biomedical Signal Processing: Isolating baseline drift from electrocardiogram (ECG) recordings or filtering photoplethysmogram (PPG) traces where non-linear phase distortion would artificially distort peak morphology.
  • Acoustics and Vibration Analysis: Processing accelerometer telemetry and audio signals using equiripple or windowed bandpass filters to isolate structural resonances.
  • Laboratory Instrumentation: Conditioning sensor streams prior to spectral density estimation or parameter estimation in signal analysis pipelines.

Install or access (official source only)

FIR filter design routines in MATLAB are provided primarily through the official Signal Processing Toolbox by MathWorks:

  • Base MATLAB: Provides basic 1-D rational transfer function filtering via the built-in filter function.
  • Signal Processing Toolbox: Required for classical FIR design functions (fir1, fir2, firls, firpm), modern filter objects (designfilt), frequency response visualization (freqz, fvtool), and forward-backward zero-phase filtering (filtfilt). Confirm toolbox installation in the MATLAB Command Window by running:
    license('test', 'Signal_Toolbox')
    ver('signal')
  • Access Routes: Obtain access via an institutional campus-wide site license or through a MathWorks account managed under your institution’s software license agreement. Add-on toolboxes can be installed directly through the MATLAB Add-On Explorer (Home Tab → Add-Ons → Get Add-Ons).

Step-by-step task

The following five-step workflow demonstrates how to design, analyze, and apply a 48th-order lowpass FIR filter to experimental time-series data using both classical windowing (fir1) and modern filter objects (designfilt).

  1. Define sampling parameters and target cutoff: Establish your sampling frequency in Hz and calculate the normalized cutoff frequency. In MATLAB, normalized frequency spans from 0 to 1, where 1 corresponds to the Nyquist frequency (half the sampling rate, $f_s / 2$):

    % Sampling parameters
    fs = 1000;              % Sampling frequency (Hz)
    t = 0:1/fs:2;           % Time vector (2 seconds)
    f_cutoff = 100;         % Target lowpass cutoff (Hz)
    
    % Normalized cutoff frequency (Wn in range [0, 1])
    Wn = f_cutoff / (fs / 2);  % Wn = 100 / 500 = 0.20
  2. Design filter coefficients with fir1: Specify the filter order $n$. The resulting numerator coefficient vector b contains $n + 1$ taps. By default, fir1 applies a symmetric Hamming window and normalizes passband center gain to unity (0 dB):

    % 48th-order lowpass FIR filter using default Hamming window
    n = 48;
    b = fir1(n, Wn, 'low');

    To use an alternative window function such as a Blackman or Kaiser window, pass a window vector of length $n + 1$:

    % Using a Kaiser window with shape factor beta = 5.65
    w_kaiser = kaiser(n + 1, 5.65);
    b_kaiser = fir1(n, Wn, 'low', w_kaiser);
  3. Alternative: Specify requirements with designfilt: For workflows requiring explicit passband ripple and stopband attenuation constraints rather than arbitrary filter orders, use the high-level designfilt function:

    % Minimum-order equiripple lowpass FIR filter
    d = designfilt('lowpassfir', ...
        'PassbandFrequency', 80, ...
        'StopbandFrequency', 120, ...
        'PassbandRipple', 0.5, ...
        'StopbandAttenuation', 50, ...
        'SampleRate', fs);
  4. Inspect frequency response with freqz: Verify the magnitude and phase response before filtering data to ensure sufficient stopband rejection and linear phase roll-off:

    % Compute 512-point complex frequency response
    [h, f] = freqz(b, 1, 512, fs);
    
    % Plot magnitude response in decibels
    figure;
    subplot(2, 1, 1);
    plot(f, 20*log10(abs(h)), 'LineWidth', 1.5);
    grid on;
    title('FIR Filter Magnitude Response');
    xlabel('Frequency (Hz)');
    ylabel('Magnitude (dB)');
    
    % Plot phase response
    subplot(2, 1, 2);
    plot(f, unwrap(angle(h)) * (180/pi), 'LineWidth', 1.5);
    grid on;
    title('Linear Phase Response');
    xlabel('Frequency (Hz)');
    ylabel('Phase (degrees)');
  5. Filter the signal and compensate for delay: Apply the filter to your measurement signal. For real-time or causal processing, use filter, noting that it delays the signal by $n / 2$ samples. For offline analysis where delay cannot be tolerated, use filtfilt for zero-phase forward-backward filtering:

    % Generate synthetic noisy signal (50 Hz signal + 250 Hz noise)
    x = sin(2*pi*50*t) + 0.5*sin(2*pi*250*t);
    
    % Method A: Causal filtering (delays signal by n/2 samples)
    y_causal = filter(b, 1, x);
    delay_samples = n / 2;
    
    % Method B: Zero-phase filtering (offline research analysis)
    y_zerophase = filtfilt(b, 1, x);

Output and how to read it

Working with FIR filters in MATLAB produces numerical vectors and diagnostic graphical objects:

  • Filter Coefficients (b): A $1 times (n + 1)$ row vector representing the impulse response $h[k]$ of the filter. For symmetric linear-phase Type I (odd order, even length) and Type II (even order, odd length) filters, the coefficient values are symmetric around the center tap ($b[k] = b[n – k]$). In a pure FIR system, the denominator transfer function vector $a$ is scalar 1, contrasting with rational polynomial representations encountered in transfer function models.
  • Magnitude Response: Evaluated in decibels ($20 log_{10} |H(f)|$). A well-designed FIR filter displays a passband near 0 dB, a smooth transition band, and stopband sidelobes suppressed below your target threshold (for example, $-53text{ dB}$ for a Hamming window).
  • Phase and Group Delay: Symmetric FIR filters exhibit a straight downward phase slope against frequency, indicating strictly linear phase. The group delay $tau_g = -dtheta / domega$ is constant and equals exactly $n / 2$ samples. In contrast, IIR filters introduce frequency-dependent group delay that disperses signal peaks.
  • Filter Object (digitalFilter): When generated with designfilt, inspect filter properties using info(d) or open the interactive Filter Visualization Tool using fvtool(d) or fvtool(b, 1) to inspect pole-zero constellations, step response, and impulse response. Synthetic noise benchmarks can be evaluated against signal degradation models such as MATLAB imnoise.

Troubleshooting

When implementing FIR filters in MATLAB, researchers commonly encounter three configuration traps:

  • Order Increment Warning on Highpass or Bandstop Filters:

    Symptom: MATLAB displays the warning Warning: Filter order must be even; order increased by 1.

    Cause: Linear-phase FIR filters with odd order $n$ (Type II filters) have an antisymmetric frequency response at the Nyquist frequency, forcing $H(pi) = 0$. Consequently, highpass and bandstop filters cannot pass frequencies up to Nyquist when $n$ is odd. To satisfy passband constraints at Nyquist, the filter order must be even (giving an odd number of coefficients, Type I FIR). MATLAB automatically increments odd orders by 1 to prevent invalid designs.

    Fix: Always pass an even integer for $n$ when designing highpass or bandstop filters with fir1.

  • Phase Shift Distorting Feature Latencies:

    Symptom: Event peaks in the filtered signal y appear shifted later in time relative to the raw input x.

    Cause: Causal filtering with filter(b, 1, x) introduces a constant temporal delay of $n / (2 cdot f_s)$ seconds ($n/2$ samples).

    Fix: For offline analysis, replace filter with filtfilt(b, 1, x) to achieve zero-phase response. If causal filtering is required (such as in online feedback loops), align timestamps by shifting the filtered signal backward by $n/2$ samples: y_aligned = y_causal((n/2 + 1):end);.

  • End-Point Transients and Ringing Artifacts:

    Symptom: Large transient oscillations appear at the beginning and end of the filtered time series.

    Cause: The convolution operation assumes zeros outside the boundaries of finite-length vectors, causing filter step responses at signal edges.

    Fix: Pad your data with mirrored boundary conditions prior to filtering, or ensure recording buffers extend beyond your experimental epoch of interest. The filtfilt function applies reflection padding automatically by default.

Free alternatives

Researchers operating in open-science environments or containerized high-performance computing clusters without MATLAB licenses can implement identical FIR designs using open-source tools:

Tool / Environment Package / Module Core FIR Function Design Method and Characteristics Licensing
GNU Octave signal fir1(n, w, type, window) Direct syntax drop-in for MATLAB fir1; supports standard window types and normalized cutoff frequencies. GNU GPLv3
Python scipy.signal firwin(numtaps, cutoff, window, fs) Window-based linear-phase FIR design; accepts absolute frequency in Hz when fs is specified; returns numtaps ($n + 1$) coefficients. Suitable alongside numerical tools like NumPy polyfit. BSD 3-Clause
Julia DSP.jl digitalfilter(response, FIRWindow(window)) High-performance typed DSP library; designs windowed FIR filters and applies them via filt or filtfilt. MIT License
R signal fir1(n, w, type, window) Port of Octave signal processing routines; useful for bio-signal workflows requiring R matrix operations. GNU GPLv2

FAQ

What is the difference between fir1 and designfilt in MATLAB?

fir1 is a classical function that calculates a vector of filter coefficients b based on a fixed filter order $n$, normalized cutoff frequency, and a specified window vector. designfilt is a modern, object-based function in the Signal Processing Toolbox that allows researchers to specify practical performance constraints (such as maximum allowable passband ripple in dB and minimum stopband attenuation in dB) and automatically calculates the required minimum filter order.

How do I achieve zero-phase distortion with an FIR filter?

Use the filtfilt(b, 1, x) function from the Signal Processing Toolbox. It performs forward-backward filtering: the signal is filtered once, reversed in time, filtered again, and reversed back. This completely cancels phase distortion, resulting in zero phase lag across all frequencies. Note that this doubles the effective filter order and squares the attenuation.

Why does MATLAB increase the order of a highpass FIR filter by 1?

Symmetric linear-phase FIR filters with odd order $n$ (Type II filters) mathematically force a zero at the Nyquist frequency ($omega = pi$). A highpass filter requires non-zero gain at Nyquist. To satisfy this requirement, MATLAB automatically increases an odd order to the nearest even integer, resulting in a Type I filter with an odd number of coefficients ($n + 1$).

How do I choose between FIR and IIR filters in research data analysis?

Choose an FIR filter when linear phase response, waveform preservation, and unconditional stability are essential (such as in EEG, ECG, or audio analysis). Choose an IIR filter (such as Butterworth or Chebyshev) when processing resources are constrained, steep transition roll-off is required with low computational latency, and non-linear phase distortion can be accepted or post-corrected.

Sources

Official documentation and technical standards referenced for this guide:

  • MathWorks: fir1 Reference Documentation. MathWorks Signal Processing Toolbox. Available at: https://www.mathworks.com/help/signal/ref/fir1.html (checked 2026-11-08).
  • MathWorks: designfilt Reference Documentation. MathWorks Signal Processing Toolbox. Available at: https://www.mathworks.com/help/signal/ref/designfilt.html (checked 2026-11-08).
  • MathWorks: filter and filtfilt Reference Documentation. MathWorks Documentation. Available at: https://www.mathworks.com/help/signal/ref/filtfilt.html (checked 2026-11-08).
  • SciPy Community: scipy.signal.firwin Documentation. SciPy v1.14 Reference Guide. Available at: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.firwin.html (checked 2026-11-08).
  • GNU Octave Forge: fir1 Function Reference. GNU Octave Signal Package. Available at: https://octave.sourceforge.io/signal/function/fir1.html (checked 2026-11-08).

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about FIR MATLAB: Filter Design with fir1 and freqz

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →