introduction to matlabbenesco.ch/benesco_new/wp-content/uploads/2018/04/... · 18-09-2015 ·...
TRANSCRIPT
Introduction to MATLAB Importing data, down sampling, filtering, plotting signals
BENESCO Lecture Series on Signal Analysis
by Dr. Mojtaba Bandarabadi email: [email protected]
Inselspital, Bern, 18 Sept. 2015
BENESCO, Department of Neurology, Inselspital, Bern
Outline• What is MATLAB
• Importing data into MATLAB
• Downsampling
• Preprocessing
• Digital filters
• Fast Fourier Transform (FFT)
• Plotting data
• Feature extraction
• Homework
2
BENESCO, Department of Neurology, Inselspital, Bern
What is MATLAB?• High level programming language and computing environment
• Mathematical functions for
• Linear algebra, statistics, differential equations, …
• Signal analysis, image processing, …
• Frequency domain analysis, Fourier transform, …
• Optimisation
• Visualising data
• Development tools
• Building applications using GUI
3
BENESCO, Department of Neurology, Inselspital, Bern
MATLAB environment
4
BENESCO, Department of Neurology, Inselspital, Bern
First step - Importing data to workspace• Loading data into MATLAB; supported formats by default:
5
BENESCO, Department of Neurology, Inselspital, Bern
First step - Importing data to workspace• For formats not supported by default, use third-party functions
• By googling you can find out something to convert your data into MATLAB!
• MATLAB function and code to load Neuralynx data
[Timestamps, samples, Header] = Nlx2MatCSC('sampleData.ncs', [1 0 0 0 1], 1, 1); samples = samples(:);
% ADBitVolts is scaling factor, obtained from the Header ADBitVolts = char(Header(16)); ADBitVolts = str2double(ADBitVolts(13:38))*1000000; samples = samples*ADBitVolts;
% Obtain sampling rate of of raw signal from the Header sampRate = char(Header(14)); sampRate = str2double(sampRate(20:end));
6
BENESCO, Department of Neurology, Inselspital, Bern
Variables in MATLAB• are in forms of matrices
• scalar (1x1)
• vectors (1xn or nx1)
• 2D (mxn), more-Dim (mxnx…)
• The class of the matrix
• identified by the data type stored in the matrix
• can be numeric, character, date and time, structure, cell array, table, …
7
Fig. Different type of variables in workspace
BENESCO, Department of Neurology, Inselspital, Bern
Functions in MATLAB• You can write your own functions to use them regularly
8
Function nameOutput variable Input variables
Des
crip
tion
of
func
tion
(opt
iona
l)Yo
ur a
lgor
ithm
BENESCO, Department of Neurology, Inselspital, Bern
Downsampling - why should we do it?• To reduce size of data, recorded in high sampling rates
• Recorded biosignal at 32 KHz, but we want to study frequencies up to 250 Hz.
• Computational cost of some analysis methods is very high, specifically in long-term continuous recordings.
• Two function for downsampling (DS) in MATLAB are
• y = downsample(x,n); % xis input signal and n is DS ratio
• y = decimate(x,n);
9
BENESCO, Department of Neurology, Inselspital, Bern
Downsampling - aliasing problem• Downsampling by keeping nth sample may introduce aliasing
(‘downsample’ function).
• Aliasing occurs when new sampling rate is very low to capture high frequency content.
• HF contents leaks into lower frequencies (results in wrong FFT)
10
Fig. Aliasing problem by downsampling
BENESCO, Department of Neurology, Inselspital, Bern
Downsampling - aliasing problem• Solution: applying a lowpass filter before downsampling, with
cutoff frequency of half of new sampling rate.
• ‘decimate’ by nature do this. Use it instead of ‘downsample’!
6.64 6.645 6.65 6.655 6.66 6.665 6.67
−200
−150
−100
−50
0
50
100
150
time (sec)
rawDS by downsampleDS by decimate
11
Fig. Raw data and its downsampled versions using ‘downsample’ and ‘decimate’ functions of MATLAB
BENESCO, Department of Neurology, Inselspital, Bern
Preprocessing - removing linear trends• A linear trend indicates a systematic increase/decrease in data.
Can result from sensor drift, for example.
• ‘detrend’ function subtracts the mean or a best-fit line (in the least-squares sense) from your data.
12
Fig. Removing linear trends of a signal. Source: MATLAB help documentation
BENESCO, Department of Neurology, Inselspital, Bern
Digital filters• Why do we need filter signals?
• Obtain desired frequency components for further analysis
• Removing interferences
EEG
Delta
0.5-4 Hz
SWS
< 1 Hz
Spindle
11-16 Hz
0.2
mV
1000 ms
NREM
13
Fig. Ten seconds of EEG signal recorded from mouse during non-REM sleep stage. Filtered to extract desired frequency components. SWS (Slow Wave Sleep), Delta activity and Spindling
BENESCO, Department of Neurology, Inselspital, Bern
Digital filters• Filter design is the process of creating the filter coefficients to meet
specific filtering requirements.
• Two types are IIR and FIR
• Infinite impulse response (IIR)
• Finite impulse response (IIR)
• Main advantage of IIR over FIR filters
• provide desired specifications with a much lower filter order.
• Main advantage of FIR over IIR filters
• can have exactly linear phase.
14
BENESCO, Department of Neurology, Inselspital, Bern
IIR filter design in MATLAB
Filter name function in MATLAB
Butterworth [b,a] = butter(order,Wn,ftype)
Chebyshev type I [b,a] = cheby1(order,Rp,Wn,ftype)
Chebyshev type II [b,a] = cheby2(order,Rs,Wn,ftype)
Elliptic [b,a] = ellip(order,Rp,Rs,Wn,ftype)
Wn: normalized cutoff frequency ftype: type of filter; ‘low’, ‘high’, ‘stop’, or bandpass filter
15
BENESCO, Department of Neurology, Inselspital, Bern
IIR filter design in MATLAB• Examples of lowpass IIR filters of order 8.
16
Fig. Frequency response of different lowpass IIR filters with same order of 8.
BENESCO, Department of Neurology, Inselspital, Bern
FIR filter design in MATLAB
17
Description function in MATLAB
Window-based FIR filter design b = fir1(order,Wn,ftype)
Frequency sampling-based FIR filter design b = fir2(order,Wn,ftype)
Least square linear-phase FIR filter design b = firls(n,f,a,ftype)
… …
BENESCO, Department of Neurology, Inselspital, Bern
Applying designed filters• There are several functions to apply designed filter on signal
• y = filter(b,a,x) - x: input, y: output, b and a: filter coefficients
• y = filtfilt(b,a,x) - performs zero-phase filtering by processing the input data in both the forward and reverse directions.
• ‘filtfilt’ function is preferred over ‘filter’ function, as it does not induce phase shift on the filtered signal.
• very important for accurate measuring of synchronisation between two signals
• But cannot be applied for real-time processing (rare cases)
18
BENESCO, Department of Neurology, Inselspital, Bern
Comparing ‘filter’ and ‘filtfilt’
3300 3350 3400 3450 3500 3550 3600
−300
−200
−100
0
100
200
300
400
500
600
rawfilterfiltfilt
% MATLAB code % Sampling frequency of raw data is 500 Hz % Lowpass filter with cutoff frequency of 10 Hz
[b,a] = butter(4, 10/(500/2), 'low'); DeciSamplesFilt = filter(b,a, DeciSamples); DeciSamplesFiltFilt = filtfilt(b,a, DeciSamples);
plot(DeciSamples, 'k', 'LineWidth', 1.5); hold on plot(DeciSamplesFilt, 'b', 'LineWidth', 1.5); plot(DeciSamplesFiltFilt, 'r', 'LineWidth', 1.5) legend('raw', 'filter', 'filtfilt')
19
Fig. Lowpass filtered signal with cutoff frequency of 10 Hz using ‘filter’ and ‘filtfilt’ functions.
BENESCO, Department of Neurology, Inselspital, Bern
Discrete Fourier Transform (DFT)• Any waveform can be expressed as a sum of sinusoidal waves!
• FT breaks a signal into its related sine waves
18
The more frequencies you use – the closer you get to the original signal
! 1
! 2
! 3
! 10
Remember the relation –
An abrupt change in the time domain will demand a wide range of frequencies to be reconstructed from.
" Use the time constants of the phenomenon you’re looking for to determine your sampling rate + a factor for increased resolution
1~t
f△△
20
Fig. Representing a sawtooth as sum of 10 sine waves. Source: Wikipedia
BENESCO, Department of Neurology, Inselspital, Bern
Fast Fourier Transform (FFT)• FFT is an algorithm to calculate DFT
0 50 100 150 200 2500
0.5
1
1.5
2
2.5
3
3.5
frequency (Hz)
|P1(
f)|
rawHighpassBandpass
0 5 10 15 20 25 30 350
0.5
1
1.5
2
2.5
3
frequency (Hz)
|P1(
f)|
rawHighpassBandpass
10 20 30 40 50 60 70 80 90 1000
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
frequency (Hz)
|P1(
f)|
rawHighpassBandpass
21
Fig. FFT of raw, highpass filtered (> 30 Hz) and bandpass filtered (6-9 Hz) signals using FIR filters designed by ‘fir1’ function
BENESCO, Department of Neurology, Inselspital, Bern
Plot data in MATLAB
22
Fig. Common graphic functions in MATLAB (source: MATLAB help documentation)
BENESCO, Department of Neurology, Inselspital, Bern
Feature extraction from signals• Measured signal is output of a system
• Feature extraction
• transforms raw data into more informative signatures of a system
• reduce size of raw data
• Next step: we can use machine learning algorithms
23
BENESCO, Department of Neurology, Inselspital, Bern
Feature extraction from signals• Features can be categorized in different ways
• Linear or nonlinear
• Number of involved channels
• univariate (extracted from one signal)
• bivariate (two signals)
• multivariate (more than two signals simultaneously).
• Time domain, frequency domain, or time-frequency domain.
24
BENESCO, Department of Neurology, Inselspital, Bern
Homework• Download the related exercise (18.09.2015) here.
• Go through the code and try to understand each part.
• Load different file formats provided. Try to load your data if any.
• Downsample data using two provided functions, and compare results.
• Filter signal using lowpass, highpass, bandpass and stopband
filters in several frequency bands, and plot the results.
• Apply Fast Fourier Transform (FFT) on the original signal and the filtered ones to see the effects of filtering in frequency domain.
25
BENESCO, Department of Neurology, Inselspital, Bern
Questions?
26