0
0
MatlabHow-ToBeginner ยท 4 min read

How to Design Filters in MATLAB: Step-by-Step Guide

To design a filter in MATLAB, use built-in functions like fir1 for FIR filters or designfilt for more advanced filters. Specify filter type, order, and cutoff frequencies, then apply the filter to your data using filter or fvtool to visualize the response.
๐Ÿ“

Syntax

Here are common MATLAB commands to design filters:

  • b = fir1(n, Wn): Designs an FIR filter of order n with normalized cutoff Wn.
  • d = designfilt('lowpassfir', 'FilterOrder', n, 'CutoffFrequency', Wn): Designs a filter object with specified properties.
  • y = filter(b, 1, x): Applies filter coefficients b to signal x.
  • fvtool(b,1): Visualizes the filter frequency response.
matlab
b = fir1(n, Wn)
d = designfilt('lowpassfir', 'FilterOrder', n, 'CutoffFrequency', Wn)
y = filter(b, 1, x)
fvtool(b,1)
๐Ÿ’ป

Example

This example designs a lowpass FIR filter of order 20 with cutoff frequency 0.4 (normalized), applies it to a noisy signal, and plots the original and filtered signals.

matlab
fs = 1000; % Sampling frequency
n = 20; % Filter order
Wn = 0.4; % Normalized cutoff frequency (0 to 1)

% Design lowpass FIR filter
b = fir1(n, Wn);

% Create a noisy signal
t = 0:1/fs:1-1/fs;
x = sin(2*pi*50*t) + 0.5*randn(size(t));

% Filter the signal
y = filter(b, 1, x);

% Plot original and filtered signals
plot(t, x, 'b', t, y, 'r')
legend('Original Signal', 'Filtered Signal')
title('Lowpass FIR Filter Example')
xlabel('Time (seconds)')
ylabel('Amplitude')
Output
A plot window showing two lines: a noisy blue signal and a smoother red filtered signal.
โš ๏ธ

Common Pitfalls

Common mistakes when designing filters in MATLAB include:

  • Using cutoff frequency values outside the normalized range 0 to 1 (where 1 corresponds to Nyquist frequency).
  • Choosing filter order too low, resulting in poor filtering performance.
  • Not visualizing the filter response to verify design.
  • Applying filter coefficients incorrectly (e.g., mixing up numerator and denominator).
matlab
% Wrong cutoff frequency (greater than 1)
b_wrong = fir1(20, 1.5); % This will cause an error

% Correct cutoff frequency
b_right = fir1(20, 0.4);
Output
Error using fir1: Cutoff frequency must be between 0 and 1.
๐Ÿ“Š

Quick Reference

Filter design tips:

  • Use fir1 for simple FIR filters.
  • Use designfilt for flexible filter types.
  • Always normalize cutoff frequencies by Nyquist frequency (half the sampling rate).
  • Visualize filters with fvtool before applying.
  • Test filters on sample signals to check performance.
โœ…

Key Takeaways

Use MATLAB functions like fir1 and designfilt to create filters easily.
Always specify cutoff frequencies normalized to Nyquist frequency (0 to 1).
Visualize your filter with fvtool to understand its frequency response.
Test filters on sample data to ensure they work as expected.
Avoid cutoff frequencies outside the valid range to prevent errors.