Simple Filter Examples in MATLAB with Implementation Details

Resource Overview

Simple Filter Examples in MATLAB: A Practical Guide to FIR Filter Design Using fir1 and fir2 Functions

Detailed Documentation

When designing digital filters in MATLAB, fir1 and fir2 are two commonly used functions that belong to the Finite Impulse Response (FIR) filter design toolkit. These functions simplify the filter creation process and are particularly suitable for scenarios requiring rapid implementation of filtering effects. The implementation involves generating filter coefficients that can be directly applied to signal data using MATLAB's filter function.

Basic Application of fir1 Function fir1 is used to design standard low-pass, high-pass, band-pass, or band-stop FIR filters. Users only need to specify the cutoff frequency and filter order, and the function generates filter coefficients based on the window method (such as Hamming window). For example, when designing a low-pass filter, the cutoff frequency must be normalized between 0 and 1 (where 1 corresponds to the Nyquist frequency). A typical implementation would be: n = 60; % Filter order fc = 0.3; % Normalized cutoff frequency b = fir1(n, fc); % Returns filter coefficients The resulting coefficients can then be applied to signals using y = filter(b, 1, x).

Extended Functionality of fir2 Unlike fir1, fir2 supports custom frequency responses. By inputting frequency points and corresponding amplitude vectors, users can design multi-band or arbitrarily shaped response filters. For instance, when implementing a filter that enhances specific frequency bands while attenuating others, fir2 provides greater flexibility. The implementation follows this pattern: f = [0 0.3 0.4 1]; % Frequency points m = [1 1 0 0]; % Desired amplitudes b = fir2(n, f, m); % Designs filter with custom response This approach uses frequency sampling method to approximate the desired frequency response.

Practical Usage Recommendations When selecting filter order, balance computational efficiency against filtering performance: higher orders yield steeper transition bands but increase latency and computational load. After design, use the freqz function to visualize the frequency response and verify if it meets expectations. The validation code would be: [h, w] = freqz(b, 1); % Frequency response plot(w/pi, 20*log10(abs(h))); % Plot magnitude response

These functions eliminate complex mathematical derivations and are ideal for rapid prototyping. However, note that they are based on the window method and may not be suitable for applications requiring extremely precise specifications (for steep cutoffs, consider equiripple design methods like remez or firpm).