Matlab Design Digital Filter
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Science and research
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured workflow for designing and validating digital filters within MATLAB. It guides users through signal analysis, architecture selection, and verification, ensuring that filter designs meet specific frequency and magnitude requirements. The skill emphasizes the use of standard MATLAB functions like designfilt and filterAnalyzer, while enforcing best practices for numerical stability and frequency-aware design.
What it does
- Designs FIR and IIR filters including lowpass, highpass, bandpass, bandstop, and notch types.
- Provides a systematic workflow for signal analysis and architecture selection.
- Facilitates visual comparison of filter designs using Filter Analyzer.
- Enforces best practices for numerical stability, such as using SOS forms for IIR filters.
- Includes validation steps to verify filter performance against specifications.
- Supports both streaming and offline filtering implementation strategies.
When to use it
- When you need to clean up noisy signals or remove specific interference.
- When designing digital filters with specific frequency and ripple requirements.
- When comparing different filter architectures like FIR versus IIR.
- When working on streaming or batch signal processing pipelines.
Advantages
- Ensures consistent design methodology through a preflight and verification checklist.
- Promotes numerical stability by recommending specific filter forms.
- Integrates directly with MATLAB's signal processing and DSP toolboxes.
- Provides clear guidance on handling narrow transition bands.
Usage examples
- “Design a lowpass filter for a 1000 Hz signal with a 200 Hz cutoff.”
- The agent will ask for the sample rate (Fs), filter mode (streaming vs offline), and phase requirements before generating the design code.
- “How do I compare two different filter designs in MATLAB?”
- The agent will guide you to use the filterAnalyzer function and provide the necessary steps to visualize and compare their magnitude and group delay responses.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/matlab/matlab-design-digital-filter/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-design-digital-filter.zip -d .agents/skills
Documentation by MathWorks
Design Digital Filters in MATLAB
Design, implement, and validate digital filters using Signal Processing Toolbox and DSP System Toolbox. Choose the right architecture (single-stage vs efficient alternatives), generate correct code, and verify the result with plots and numbers.
When to Use
Designing lowpass, highpass, bandpass, bandstop, or notch filters
Cleaning up noisy signals or removing interference
Choosing between FIR and IIR filter architectures
Comparing filter designs in Filter Analyzer
Building streaming (real-time) or offline (batch) filtering pipelines
Handling narrow transition bands with multirate or IFIR approaches
When NOT to Use
Adaptive filtering (LMS, RLS) -- use Signal Processing Toolbox docs directly
Audio-specific processing (equalization, room correction) -- use Audio Toolbox
Image filtering (2D convolution, morphological ops) -- use Image Processing Toolbox
General spectral analysis without filtering intent -- FFT/periodogram docs suffice
Key Rules
Read references/INDEX.md before writing any filter design code.
Always write to .m files. Never put multi-line MATLAB code directly in
evaluate_matlab_code. Write to a.mfile, run withrun_matlab_file, edit on error.Preflight before ANY MATLAB call. Before calling any function listed in INDEX.md, read the required quick-ref first. State
Preflight: [files]at the top of the response.Do not guess key requirements. If Mode (streaming vs offline) or Phase requirement is not stated, ask.
No Hz designs without Fs. If
Fsis unknown, stop and ask (unless the user explicitly wants normalized frequency).Always pin the sample rate. Use
designfilt(..., SampleRate=Fs)andfreqz(d, [], Fs).IIR stability: Prefer SOS/CTF forms (avoid high-order
[b,a]polynomials).
Preflight Procedure
List MATLAB functions to call
Check
references/INDEX.mdfor each (function-level + task-level tables)Read required quick-ref files
State at response top:
Preflight: quick-ref/filter-analyzer.md, quick-ref/designfilt.md(orPreflight: none required)
Workflow
Phase 1: Signal Analysis
Analyze input data via MCP (spectrum, signal length, interference location)
Compute
trans_pctand identify interference characteristics
Phase 2: Clarify Intent
After signal analysis, ask Mode + Phase if not stated:
Mode: streaming (causal) | offline (batch)
Phase: zero-phase | linear-phase | don't-care
Wait for answer before showing any approach comparison or overview.
Phase 3: Architecture Selection
Open
references/efficient-filtering.mdiftrans_pct < 2%Show only viable candidates given Mode + Phase constraints
Explicitly state excluded families with one-line reason
Use Filter Analyzer for visual comparison
Design Intake Checklist
Required signal + frequency spec (cannot proceed without)
Fs(Hz)Response type: lowpass / highpass / bandpass / bandstop / notch
Edge frequencies in Hz
If any item is missing, ask.
Required intent for architecture choice (ask if unknown)
Mode: streaming (causal) | offline (batch)
Phase: zero-phase | linear-phase | don't-care
Magnitude constraints:
Rp_dBpassband ripple (default 1 dB),Rs_dBstopband attenuation (default 60 dB)
If Mode or Phase is unknown, ask 1-2 clarifying questions and stop.
Architecture Checkpoint
Compute and state before finalizing an approach:
trans_bw = Fstop - Fpasstrans_pct = 100 * trans_bw / FsM_max = floor(Fs/(2*Fstop))(only meaningful for lowpass-based multirate)
Decision rule:
trans_pct > 5%-- single-stage FIR or IIR is usually fine2% <= trans_pct <= 5%-- single-stage possible; mention efficient alternatives if cost/latency matterstrans_pct < 2%-- stop and do a narrow-transition comparison (seereferences/quick-ref/efficient-filtering.md)
Design + Verify
Feasibility check -- Let
designfiltchoose minimum order, then queryfiltord(d). Optionally usekaiserord/firpmordfor FIR length estimates.Design candidates -- Prefer
designfilt()with explicitRp/RsandSampleRate=Fs. Streaming IIR: useSystemObject=true. Offline zero-phase:filtfilt()is allowed but state that it squares the magnitude response.Compare visually -- Use
filterAnalyzer()for comparing 2+ designs. Readreferences/quick-ref/filter-analyzer.mdfirst. Minimum displays: magnitude + group delay.Verify with numbers -- Worst-case passband ripple and stopband attenuation vs spec. For
filtfilt(), verify the effective response (magnitude squared).Deliver the output -- Specs recap, derived metrics, chosen architecture + why, MATLAB code, verification snippet + results, implementation form.
Key Functions
| Function | Purpose |
|---|---|
designfilt() | Primary filter design (FIR and IIR, all response types) |
filterAnalyzer() | Visual comparison of 2+ filter designs |
freqz(), grpdelay() | Frequency response and group delay analysis |
filtfilt() | Zero-phase offline filtering |
dsp.SOSFilter | Streaming IIR via SystemObject=true |
designMultirateFIR() | Multirate decimator/interpolator design |
ifir() | Interpolated FIR for narrow transitions at constant rate |
cost() | MPIS (MultiplicationsPerInputSample) on DSP System objects |
kaiserord(), firpmord() | FIR order estimation |
Conventions
Always specify
SampleRate=Fsindesignfilt()and plot in Hz withfreqz(d, [], Fs)Use
filterAnalyzer()for multi-filter comparison, not customfreqz/grpdelayplotsUse SOS form for IIR (avoid
[b,a]for order > 8)Use
tiledlayout/nexttilefor multi-panel figures (notsubplot)
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md6.1 KiB
- manifest.yaml473 B
- references/INDEX.md2.9 KiB
- references/best-practices.md7.8 KiB
- references/efficient-filtering.md14.4 KiB
- references/filter-analyzer.md18.1 KiB
- references/multirate.md13.2 KiB
- references/multistage-ifir.md8.5 KiB
- references/patterns.md16.2 KiB
- references/quick-ref/designfilt.md6.0 KiB
- references/quick-ref/efficient-filtering.md6.1 KiB
- references/quick-ref/filter-analyzer.md3.0 KiB
- references/quick-ref/general-iir-fir.md3.0 KiB
- references/quick-ref/multirate-offline.md2.3 KiB
- references/quick-ref/multirate-streaming.md3.6 KiB
- references/quick-ref/multistage-ifir.md2.8 KiB
references/best-practices.md
Filter Design Best Practices
Guidelines for robust filter design, validation workflows, and professional interactions. Consult this file when you need guidance on methodology and approach.
Table of Contents
Core Principles
Provide Complete Solutions
Validation Workflow
Architecture Decision Workflow
Streaming vs Offline
Performance Optimization
Quick Lookup
Core Principles
Always Consider
Sample Rate Implications
Frequency specifications are relative to Fs/2 (Nyquist)
Narrow transition bands (< 2% of Fs) require special handling
Plot in Hz for clarity:
freqz(d, [], Fs)
Filter Order vs Performance Trade-offs
Higher order = sharper cutoff but more computation
IIR = fewer coefficients but non-linear phase
FIR = linear phase but longer filters
Computational Efficiency for Real-Time
Prefer IIR for streaming with sharp cutoff
Use multistage for narrow transition bands
Consider
fftfilt()for long FIR (> 100 taps)
Numerical Stability for IIR
Always use SOS or CTF form (not
[b,a])Use
designfilt()which handles stability internallyFor high-order IIR (> 8), verify pole locations
Provide Complete Solutions
Every filter design response should include:
1. Design Code
d = designfilt("lowpassfir", ...
PassbandFrequency=Fpass, StopbandFrequency=Fstop, ...
PassbandRipple=Rp, StopbandAttenuation=Rs, ...
SampleRate=Fs, DesignMethod="equiripple");2. Visualization Code
figure;
freqz(d, [], Fs);
grid on;
title('Filter Response');3. Parameter Explanation
Why this filter type was chosen
Trade-offs considered
Key specifications achieved
4. Validation Steps
How to verify the design meets specs
Test signal suggestions
Performance metrics to check
Validation Workflow
Pre-Application Checks
% 1) Order (MATLAB's actual order)
fprintf("Filter order: %d\n", filtord(d));
% 2) Frequency response (Hz-aware)
Nfft = 8192;
[h, f] = freqz(d, Nfft, Fs);
mag_dB = 20*log10(abs(h) + eps);
% 3) If the final application is filtfilt(d,x), verify the *effective* response
use_filtfilt = false; % set true if you will apply filtfilt()
if use_filtfilt
mag_dB = 2*mag_dB; % |H|^2 -> dB doubles
end
% 4) Build pass/stop masks by RESPONSE TYPE
responseType = "lowpass"; % "highpass" | "bandpass" | "bandstop"
switch responseType
case "lowpass"
pass = f <= Fpass;
stop = f >= Fstop;
case "highpass"
pass = f >= Fpass;
stop = f <= Fstop;
case "bandpass"
pass = (f >= Fpass1) & (f <= Fpass2);
stop = (f <= Fstop1) | (f >= Fstop2);
case "bandstop"
pass = (f <= Fpass1) | (f >= Fpass2);
stop = (f >= Fstop1) & (f <= Fstop2);
end
% 5) Measured specs (worst-case)
Rp_meas_dB = max(mag_dB(pass)) - min(mag_dB(pass));
Rs_meas_dB = -max(mag_dB(stop));
fprintf("Measured ripple: %.3f dB (spec %.3f dB)\n", Rp_meas_dB, Rp);
fprintf("Measured stopband attenuation: %.1f dB (spec %.1f dB)\n", Rs_meas_dB, Rs);
% 6) Plot (optional but recommended)
figure; plot(f, mag_dB); grid on;
xlabel("Frequency (Hz)"); ylabel("Magnitude (dB)");
title("Magnitude Response (verified in Hz)");Post-Filtering Checks
% 1. Visual comparison
figure;
plot(t, x, 'b', t, y, 'r');
legend('Original', 'Filtered');
% 2. Spectrum comparison
figure;
pwelch(x, [], [], [], Fs); hold on;
pwelch(y, [], [], [], Fs);
legend('Original', 'Filtered');
% 3. SNR improvement (if ground truth available)
snr_before = 10*log10(sum(clean.^2) / sum((noisy - clean).^2));
snr_after = 10*log10(sum(clean.^2) / sum((filtered - clean).^2));
fprintf('SNR Improvement: %.1f dB\n', snr_after - snr_before);Architecture Decision Workflow
Pre-Design Check (MANDATORY)
For EVERY filter design, calculate:
% Template
% Transition width (Δf) should match the RESPONSE TYPE.
% Use the *constraining* transition (smallest transition band) in Hz.
%
% lowpass: Δf = Fstop - Fpass
% highpass: Δf = Fpass - Fstop
% bandpass: Δf = min(Fpass1 - Fstop1, Fstop2 - Fpass2)
% bandstop: Δf = min(Fstop1 - Fpass1, Fpass2 - Fstop2)
delta_f = ...; % fill based on response type (Hz)
trans_pct = 100 * (delta_f / Fs); % Transition width as % of sample rate
% FIR length heuristic (sanity check only; not a guarantee)
N_est = (Rs * Fs) / (22 * delta_f);
% Max decimation factor is straightforward for LOWPASS cases:
% M_max ≈ floor(Fs / (2 * Fstop))
% For highpass/band* cases, safe decimation depends on spectral placement and is not a single formula.
M_max = floor(Fs / (2 * Fstop)); ### Prefer MATLAB-Native FIR Order Estimators (recommended)
The heuristic `N_est = (Rs * Fs)/(22 * Δf)` is **sanity-check only**. For a more standard, MATLAB-native estimate:
- **Kaiser window estimate**: `kaiserord` (good quick order estimate for windowed FIR)
- **Equiripple estimate**: `firpmord` (order estimate for Parks–McClellan FIR)
```matlab
% Convert dB specs to linear deviations
dev_p = (10^(Rp/20)-1) / (10^(Rp/20)+1);
dev_s = 10^(-Rs/20);
% LOWPASS example (adapt f/a for other responses):
f = [Fpass Fstop]; % Hz
a = [1 0]; % desired amplitudes in each band
dev = [dev_p dev_s]; % linear deviations
[N_kaiser, Wn, beta, ftype] = kaiserord(f, a, dev, Fs);
[N_pm, fo, ao, w] = firpmord(f, a, dev, Fs);
fprintf("Order estimates: Kaiser=%d, Equiripple=%d\n", N_kaiser, N_pm);
```
**Workflow recommendation**:
1) Use `kaiserord`/`firpmord` to estimate if a single-stage FIR is plausible.
2) Design the real filter (e.g., `designfilt(..., DesignMethod="equiripple")`).
3) Verify with `freqz` + measured `Rp_meas_dB` / `Rs_meas_dB`.Decision Matrix
| trans_pct | Action |
|---|---|
| > 5% | Single-stage OK |
| 2-5% | Mention multistage option |
| < 2% | Present tradeoff to user (see quick-ref/efficient-filtering.md) |
Response Template
"Architecture check: Transition BW = X% of Fs, estimated ~Y taps. [Single-stage recommended / Multistage recommended - asking user preference]."
Streaming vs Offline
Offline Processing
Use
filtfilt()for zero-phaseUse
resample()for multirateProcess entire signal at once
No state management needed
Streaming/Real-Time
Use
dsp.SOSFilterwithSystemObject=trueOr use
ctffilt()(R2024b+) with state managementProcess frame-by-frame
Reset state when needed
Key Rule
Offline zero-phase → resample() + filtfilt()
Streaming causal → System objects + filter()
Never mix: System objects with filtfilt() = catastrophic failure
Performance Optimization
Long FIR Filters
if length(b) > 100
y = fftfilt(b, x); % FFT-based, faster
else
y = filter(b, 1, x); % Direct form OK
endNarrow Transition Bands
Consider multistage approach
Calculate efficiency gain:
(N_single) / (N_dec + N_sharp/M + N_interp)For trans_pct < 2%, multistage often 5-10x more efficient (see
quick-ref/efficient-filtering.md)
IIR Numerical Stability
Always use SOS form via
designfilt()orzp2sos()Avoid
[b,a]form for order > 8Check pole locations if stability concerns arise
Quick Lookup
| Topic | Consult |
|---|---|
| Code templates | patterns.md |
| API details | references/INDEX.md |
| Architecture decision | Pre-Design Check above |
| Offline vs streaming | Streaming vs Offline section |
| Validation | Validation Workflow section |
Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/signal-processing/matlab-design-digital-filter · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-design-digital-filter.zip