How to Apply Filter in MATLAB: Syntax and Examples
In MATLAB, you apply a filter to data using the
filter function with syntax y = filter(b, a, x), where b and a are filter coefficients and x is your input signal. This function processes the input signal x and returns the filtered output y.Syntax
The basic syntax to apply a filter in MATLAB is:
y = filter(b, a, x)
Here:
bis the numerator coefficient vector of the filter.ais the denominator coefficient vector of the filter.xis the input data vector or signal to be filtered.yis the filtered output signal.
This syntax applies a digital filter defined by b and a to the input x.
matlab
y = filter(b, a, x)Example
This example shows how to apply a simple moving average filter to a noisy signal.
matlab
x = [1 2 3 4 5 6 7 8 9 10]; b = ones(1,3)/3; % Moving average filter coefficients a = 1; % Denominator coefficient for FIR filter y = filter(b, a, x); disp(y);
Output
0.3333 1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000 8.0000 9.0000
Common Pitfalls
Common mistakes when using filter include:
- Using incorrect filter coefficients
bandawhich can distort the signal. - Confusing the order of arguments;
bcomes beforea. - Not normalizing filter coefficients when needed (e.g., for moving average).
- Applying filter to data with incompatible dimensions.
Example of a wrong and right way:
matlab
% Wrong: denominator before numerator % y = filter(a, b, x); % This is incorrect % Right: y = filter(b, a, x);
Quick Reference
| Parameter | Description |
|---|---|
| b | Numerator coefficients of the filter |
| a | Denominator coefficients of the filter |
| x | Input signal or data vector |
| y | Filtered output signal |
Key Takeaways
Use the filter function as y = filter(b, a, x) to apply digital filters in MATLAB.
Ensure filter coefficients b and a are correctly defined and ordered.
Normalize coefficients when applying filters like moving average.
Check input data dimensions to avoid errors.
Test filter output to confirm expected signal behavior.