KAHIBARO Bookshelves
Discord Login Register

18.2. Simple Filtering and Transformations

Overview

In this chapter you will work with very simple signal operations in MATLAB. The focus is on basic filtering and basic transformations that you can try immediately on vectors that represent signals. You will not need any toolbox, everything here uses core MATLAB functionality.

You will treat a one dimensional vector as a discrete time signal, for example a recorded audio snippet or any numeric sequence that changes over time. Then you will see how to smooth it, how to emphasize changes, and how to apply a simple transform in the time and frequency domains using built in operations.

Representing a Simple Signal as a Vector

A basic discrete signal in MATLAB is just a numeric vector. For example, this can represent a noisy measurement over time.

t = 0:0.001:1;              % time from 0 to 1 second with 1 ms step
x_clean = sin(2*pi*5*t);    % clean 5 Hz sine wave
noise = 0.4*randn(size(t)); % random noise
x = x_clean + noise;        % noisy signal

Here x is the noisy signal, t is the corresponding time vector, and x_clean is the underlying ideal signal. You can plot it to see the effect.

plot(t, x), xlabel('Time (s)'), ylabel('Amplitude'), title('Noisy signal')

Every operation in this chapter will take such a vector and produce a new vector that is a filtered or transformed version of it.

Simple Moving Average Smoothing

A moving average filter replaces each sample by the average of it and its neighbors. This is one of the simplest ways to smooth out noise.

One way to express a length $N$ moving average is

$$
y[k] = \frac{1}{N}\sum_{i=0}^{N-1} x[k - i].
$$

In MATLAB you can implement this with convolution using conv. For a 5 point moving average, construct a filter kernel and convolve.

N = 5;                        % filter length
h = ones(1, N) / N;           % moving average coefficients
y = conv(x, h, 'same');       % smoothed signal

The vector h contains the weights. The call conv(x, h, 'same') gives an output y of the same length as x, which is usually what you want when dealing with signals.

You can compare original and smoothed signals.

plot(t, x, 'Color', [0.8 0.8 0.8])
hold on
plot(t, y, 'b', 'LineWidth', 1.5)
hold off
legend('Noisy', 'Smoothed')
xlabel('Time (s)'), ylabel('Amplitude')
title('5-point moving average smoothing')

The moving average reduces rapid fluctuations, but it also slightly blurs sharp changes in the signal.

Using `filter` for Simple FIR Filters

The function filter applies a one dimensional digital filter to a data vector. At the simplest level, you can think of it as performing a difference equation of the form

$$
y[n] = \sum_{k=0}^{M} b_k x[n-k] - \sum_{k=1}^{N} a_k y[n-k].
$$

For a simple finite impulse response, or FIR, filter you set $a_0 = 1$ and $a_k = 0$ for $k \ge 1$. Then the output does not depend on past outputs, only on current and past inputs.

A moving average is such an FIR filter. Using filter it becomes:

b = ones(1, N) / N;    % numerator coefficients
a = 1;                 % denominator coefficient
y2 = filter(b, a, x);  % filtered output

y2 and the previous y from conv will be very similar for sufficiently long signals. filter is often convenient when you use difference equation style filters.

You can also create a simple 3 point smoothing filter with more weight on the center sample.

b = [0.25 0.5 0.25];
a = 1;
y_weighted = filter(b, a, x);

This keeps the central value more prominent while still smoothing.

Basic Difference Filtering to Emphasize Changes

Instead of smoothing, you might want to emphasize how the signal changes. A simple way to do this is to compute first differences. This is a kind of very simple high pass filter.

MATLAB has a direct function diff that computes differences between consecutive elements:

d = diff(x);                 % first difference

If $x$ represents samples at equally spaced times with spacing $\Delta t$, then d / dt approximates the derivative of the signal.

dt = t(2) - t(1);
dx_dt = d / dt;

If you prefer to use filter to build a difference filter, you can define coefficients for $y[n] = x[n] - x[n-1]$:

b = [1 -1];             % difference coefficients
a = 1;
d2 = filter(b, a, x);

d and d2 are slightly shifted relative to each other, but both indicate where the signal changes quickly. Large positive values indicate rising edges and large negative values indicate falling edges.

Basic Time Domain Transformations

Some transforms act directly in the time domain by modifying the order or sign of samples. A few very simple ones are time reversal, scaling, and shifting.

To reverse a signal in time, use indexing.

x_rev = x(end:-1:1);    % reverse order of samples

This flips the signal around its center in time.

To scale amplitude, multiply by a constant.

x_quiet = 0.5 * x;      % reduce amplitude
x_loud  = 2.0 * x;      % increase amplitude

To apply a simple shift in discrete time indexing, prepad or remove elements. For example, shifting the signal to the right by 3 samples corresponds to adding zeros at the beginning and truncating at the end.

shift = 3;
x_right = [zeros(1, shift) x(1:end-shift)];

Shifting to the left by 3 samples is similar but removes initial values.

x_left = x(shift+1:end);

For continuous time quantities that depend on t, you would usually shift by adjusting the time vector, but the core idea is that a shift in time is a reindexing of the samples.

Very Simple Frequency Domain Insight with `fft`

Without going deep into frequency analysis, you can already get a sense of frequency content of a signal with the Fast Fourier Transform using fft. This converts your time domain vector into a complex frequency domain representation.

Assume x is your signal and Fs is the sampling frequency. From the time step dt you can get Fs = 1 / dt.

dt = t(2) - t(1);
Fs = 1/dt;
N = numel(x);
X = fft(x);                  % complex spectrum
f = (0:N-1) * (Fs/N);        % frequency axis from 0 to Fs-1*Fs/N
magX = abs(X);               % magnitude spectrum

If you plot magX against f you see which frequencies contribute most strongly.

plot(f, magX)
xlim([0 50])                 % look at low frequencies
xlabel('Frequency (Hz)')
ylabel('|X(f)|')
title('Magnitude spectrum of x')

For the example signal that includes a 5 Hz sine wave, you should see a clear peak near 5 Hz. Noise spreads energy across many frequencies.

You can try the same after smoothing with the moving average filter and notice that high frequency content is reduced.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Getting Started with MATLAB
    • ☰ 1.1. What Is MATLAB and What Is It Used For
      • ☰ 1.2. Installing MATLAB and Setting Up the Environment
        • ☰ 1.3. Understanding the MATLAB Desktop Interface
          • ☰ 1.4. Command Window, Workspace, and Current Folder
            • ☰ 1.5. Basic Workflow and Running Simple Commands
              • ☰ 1.6. Getting Help and Documentation
              • ☰ 2. MATLAB Language Basics
                • ☰ 2.1. MATLAB Syntax and Expressions
                  • ☰ 2.2. Variables and Assignment
                    • ☰ 2.3. Data Types and Type Conversion
                      • ☰ 2.4. Vectors and Matrices Fundamentals
                        • ☰ 2.5. Creating and Indexing Arrays
                          • ☰ 2.6. Basic Arithmetic and Elementwise Operations
                            • ☰ 2.7. Using Built-In Constants and Functions
                            • ☰ 3. Working with Variables and the Workspace
                              • ☰ 3.1. Creating, Viewing, and Editing Variables
                                • ☰ 3.2. Workspace Browser and Variable Inspector
                                  • ☰ 3.3. Saving and Loading Data Files
                                    • ☰ 3.4. MAT-Files and Importing External Data
                                      • ☰ 3.5. Clearing Variables and Managing the Workspace
                                      • ☰ 4. Vectors, Matrices, and Arrays
                                        • ☰ 4.1. Row and Column Vectors
                                          • ☰ 4.2. Matrix Creation and Concatenation
                                            • ☰ 4.3. Indexing, Slicing, and Logical Indexing
                                              • ☰ 4.4. Matrix Operations vs Elementwise Operations
                                                • ☰ 4.5. Reshaping and Rearranging Arrays
                                                  • ☰ 4.6. Special Matrices and Functions
                                                  • ☰ 5. Basic Programming Constructs
                                                    • ☰ 5.1. Scripts vs Functions
                                                      • ☰ 5.2. Control Flow with if, elseif, else
                                                        • ☰ 5.3. Loops with for and while
                                                          • ☰ 5.4. break, continue, and return
                                                            • ☰ 5.5. Logical Expressions and Relational Operators
                                                              • ☰ 5.6. Best Practices for Clear and Readable Code
                                                              • ☰ 6. Functions in MATLAB
                                                                • ☰ 6.1. Creating Simple Functions
                                                                  • ☰ 6.2. Function Inputs and Outputs
                                                                    • ☰ 6.3. Function Files and the Path
                                                                      • ☰ 6.4. Local vs Global Variables
                                                                        • ☰ 6.5. Anonymous Functions
                                                                          • ☰ 6.6. Organizing Code into Multiple Functions
                                                                          • ☰ 7. Working with Numbers and Math
                                                                            • ☰ 7.1. Scalars and Vectorized Computations
                                                                              • ☰ 7.2. Basic Mathematical Functions
                                                                                • ☰ 7.3. Trigonometric and Exponential Functions
                                                                                  • ☰ 7.4. Complex Numbers in MATLAB
                                                                                    • ☰ 7.5. Rounding, Modulo, and Special Values
                                                                                      • ☰ 7.6. Numerical Precision and Floating Point Considerations
                                                                                      • ☰ 8. Strings, Characters, and Categorical Data
                                                                                        • ☰ 8.1. Character Arrays and String Arrays
                                                                                          • ☰ 8.2. Creating and Manipulating Strings
                                                                                            • ☰ 8.3. Converting Between Data Types and Strings
                                                                                              • ☰ 8.4. Comparing and Searching Strings
                                                                                                • ☰ 8.5. Categorical Arrays Basics
                                                                                                • ☰ 9. Tables, Structures, and Cell Arrays
                                                                                                  • ☰ 9.1. Introduction to Tables
                                                                                                    • ☰ 9.2. Creating Tables and Accessing Data
                                                                                                      • ☰ 9.3. Modifying and Joining Tables
                                                                                                        • ☰ 9.4. Structures and Nested Structures
                                                                                                          • ☰ 9.5. Cell Arrays and Cell Indexing
                                                                                                            • ☰ 9.6. Choosing the Right Container Type
                                                                                                            • ☰ 10. Importing and Exporting Data
                                                                                                              • ☰ 10.1. Reading Text and CSV Files
                                                                                                                • ☰ 10.2. Importing Excel Spreadsheets
                                                                                                                  • ☰ 10.3. Importing Data with the Import Tool
                                                                                                                    • ☰ 10.4. Exporting Data to Files
                                                                                                                      • ☰ 10.5. Working with Image and Audio Files
                                                                                                                        • ☰ 10.6. Basic File Management from MATLAB
                                                                                                                        • ☰ 11. Plotting and Visualization
                                                                                                                          • ☰ 11.1. Introduction to 2D Plotting
                                                                                                                            • ☰ 11.2. Customizing Plots and Axes
                                                                                                                              • ☰ 11.3. Multiple Plots in One Figure
                                                                                                                                • ☰ 11.4. Labels, Titles, Legends, and Annotations
                                                                                                                                  • ☰ 11.5. Plotting with Different Line and Marker Styles
                                                                                                                                    • ☰ 11.6. Saving and Exporting Figures
                                                                                                                                    • ☰ 12. Advanced Plotting for Beginners
                                                                                                                                      • ☰ 12.1. Subplots and Tiled Layouts
                                                                                                                                        • ☰ 12.2. Bar, Scatter, and Stem Plots
                                                                                                                                          • ☰ 12.3. Histograms and Density Plots
                                                                                                                                            • ☰ 12.4. 3D Plots and Surface Plots
                                                                                                                                              • ☰ 12.5. Using plottools and Interactive Editing
                                                                                                                                                • ☰ 12.6. Basics of Handle Graphics
                                                                                                                                                • ☰ 13. Working with Scripts and Live Scripts
                                                                                                                                                  • ☰ 13.1. Creating and Running Script Files
                                                                                                                                                    • ☰ 13.2. Sectioning Code and Running Sections
                                                                                                                                                      • ☰ 13.3. Live Scripts and Rich Text
                                                                                                                                                        • ☰ 13.4. Adding Equations, Images, and Outputs
                                                                                                                                                          • ☰ 13.5. Sharing and Exporting Live Scripts
                                                                                                                                                          • ☰ 14. Debugging and Code Quality
                                                                                                                                                            • ☰ 14.1. Finding and Fixing Syntax Errors
                                                                                                                                                              • ☰ 14.2. Setting Breakpoints and Stepping Through Code
                                                                                                                                                                • ☰ 14.3. Inspecting Variable Values During Execution
                                                                                                                                                                  • ☰ 14.4. Using the Editor Debugging Tools
                                                                                                                                                                    • ☰ 14.5. Using Code Analyzer and Warnings
                                                                                                                                                                      • ☰ 14.6. Writing Clean and Maintainable MATLAB Code
                                                                                                                                                                      • ☰ 15. Basic Linear Algebra with MATLAB
                                                                                                                                                                        • ☰ 15.1. Vectors and Norms
                                                                                                                                                                          • ☰ 15.2. Matrix Addition and Multiplication
                                                                                                                                                                            • ☰ 15.3. Solving Linear Systems with Backslash
                                                                                                                                                                              • ☰ 15.4. Inverses, Determinants, and Rank
                                                                                                                                                                                • ☰ 15.5. Eigenvalues and Eigenvectors
                                                                                                                                                                                  • ☰ 15.6. Using Linear Algebra Functions Safely
                                                                                                                                                                                  • ☰ 16. Data Analysis and Statistics Fundamentals
                                                                                                                                                                                    • ☰ 16.1. Descriptive Statistics and Summary Measures
                                                                                                                                                                                      • ☰ 16.2. Sorting, Filtering, and Grouping Data
                                                                                                                                                                                        • ☰ 16.3. Basic Correlation and Regression
                                                                                                                                                                                          • ☰ 16.4. Simple Data Cleaning Techniques
                                                                                                                                                                                            • ☰ 16.5. Basic Time Series Handling
                                                                                                                                                                                            • ☰ 17. Working with Time and Dates
                                                                                                                                                                                              • ☰ 17.1. Representing Dates and Times
                                                                                                                                                                                                • ☰ 17.2. Creating and Formatting datetime Arrays
                                                                                                                                                                                                  • ☰ 17.3. Date Calculations and Differences
                                                                                                                                                                                                    • ☰ 17.4. Plotting Data over Time
                                                                                                                                                                                                    • ☰ 18. Introduction to Signal and Image Handling
                                                                                                                                                                                                      • ☰ 18.1. Basic Signal Representation in MATLAB
                                                                                                                                                                                                        • ☰ 18.2. Simple Filtering and Transformations
                                                                                                                                                                                                          • ☰ 18.3. Reading, Displaying, and Writing Images
                                                                                                                                                                                                            • ☰ 18.4. Basic Image Transformations
                                                                                                                                                                                                            • ☰ 19. Automation and Scripting Tasks
                                                                                                                                                                                                              • ☰ 19.1. Batch Processing of Files
                                                                                                                                                                                                                • ☰ 19.2. Writing Reusable Utility Scripts
                                                                                                                                                                                                                  • ☰ 19.3. Using Relative Paths and the MATLAB Path
                                                                                                                                                                                                                    • ☰ 19.4. Simple User Interaction with input and disp
                                                                                                                                                                                                                    • ☰ 20. Introduction to Toolboxes
                                                                                                                                                                                                                      • ☰ 20.1. What Are Toolboxes and How to Use Them
                                                                                                                                                                                                                        • ☰ 20.2. Exploring Installed Toolboxes
                                                                                                                                                                                                                          • ☰ 20.3. Finding Functions in Toolboxes
                                                                                                                                                                                                                            • ☰ 20.4. Add-Ons and MATLAB File Exchange
                                                                                                                                                                                                                            • ☰ 21. Best Practices and Next Steps
                                                                                                                                                                                                                              • ☰ 21.1. Organizing Projects and Folders
                                                                                                                                                                                                                                • ☰ 21.2. Version Control Basics with MATLAB
                                                                                                                                                                                                                                  • ☰ 21.3. Performance Tips for Beginners
                                                                                                                                                                                                                                    • ☰ 21.4. Learning Resources and Documentation Path
                                                                                                                                                                                                                                      • ☰ 21.5. Suggested Practice Projects for Beginners