On this page

This tutorial was originally published on nbtwiki.net as companion material to Hardstone et al. (2012). It was migrated here in 2026 and extended in November 2026 with a Python route using crosci. The MATLAB code uses functions from the Neurophysiological Biomarker Toolbox (NBT), available on GitHub. For why long-range temporal correlations matter, see The Brain as a Critical System.

Please cite: R. Hardstone*, S.-S. Poil*, G. Schiavone, R. Jansen, V.V. Nikulin, H.D. Mansvelder, K. Linkenkaer-Hansen. Detrended fluctuation analysis: A scale-free view on neuronal oscillations. Frontiers in Physiology 3:450, 2012. doi:10.3389/fphys.2012.00450


Approximate time to complete: 60 minutes.

What DFA measures#

The detrended fluctuation analysis (DFA) algorithm is a scaling analysis method used to estimate long-range temporal correlations of power-law form (Peng et al., 1995; Hardstone et al., 2012). If a sequence of events has a non-random temporal structure with slowly decaying auto-correlations, DFA quantifies how slowly these correlations decay, as indexed by the DFA power-law exponent α.

Typical classes of correlations are reflected in DFA exponents of:

  • Uncorrelated sequence: α ≈ 0.5
  • Anti-correlated sequence: 0 < α < 0.5
  • Positive correlations: 0.5 < α < 1
  • Non-stationary process: 1 < α < 2 (can be modelled as fractional Brownian motion with H = α − 1)

The interest in long-range temporal correlations (LRTC) is rooted in empirical and modelling results indicating that the dynamics of self-organising multi-unit systems is characterised by fluctuations that tend to appear in a specific temporal ordering, as indexed by power-law decaying correlations. That a system is “self-organising” means that, except for some fairly slow stochastic drive, most of the fluctuations are endogenous rather than determined by strong external inputs. Self-organised criticality offers a general mechanism for the emergence of such correlations in systems of many interacting units (Linkenkaer-Hansen et al., 2001).

One hypothesis for the physical background is that ongoing activity continuously modifies the functional connectivity of the network, building up a memory of past activity that biases when and where future activity can flow (Linkenkaer-Hansen et al., 2004). As an analogy, think of water flowing down a mountain slope, carving a network of rivers that is ever changing but also sufficiently stable that it strongly influences where water can flow from day to day, month to month, year to year.

Long-range temporal correlations have been found in the amplitude modulation of human brain waves (Linkenkaer-Hansen et al., 2001), hippocampal fast network oscillations (Poil et al., 2011), and have been shown to be altered in disorders: weaker in Alzheimer’s disease (Montez et al., 2009) and abnormally strong near the seizure focus in epilepsy (Monto et al., 2007).

The interpretation of DFA crucially depends on the pre-processing of the data. In the case of EEG/MEG analysis, pre-processing consists of extracting the amplitude envelope of distinct oscillations — but DFA can also be applied to, for example, the moment-to-moment fluctuations of phase synchrony between signals, where it quantifies the possibly non-random temporal order of synchronisation (Botcharova et al., 2014).

This tutorial has three parts: computing DFA in Python, computing DFA in MATLAB with NBT, and an extended tutorial that works through the practical pitfalls on real data.


Computing DFA in Python#

crosci, maintained by the Critical-Brain-Dynamics group, implements the DFA of Hardstone et al. (2012) in Python, together with the functional excitation/inhibition ratio (fE/I; Bruining et al., 2020). Install it with pip install crosci; note that it is released under an academic licence. Then:

import numpy as np
from scipy.signal import firwin, filtfilt, hilbert
from crosci.biomarkers import DFA

fs = 250                                   # sampling frequency (Hz)
signal = np.random.default_rng(0).standard_normal((23, 300 * fs))   # 23 channels, 5 min; replace with your data

# 1. Band-pass 8-13 Hz with a zero-phase FIR filter of 2 cycles of 8 Hz (0.25 s), as in NBT
taps = firwin(int(0.25 * fs) + 1, [8, 13], pass_zero=False, fs=fs)
filtered = filtfilt(taps, 1, signal, axis=1)

# 2. Amplitude envelope
envelope = np.abs(hilbert(filtered, axis=1))

# 3. DFA, fitted over 3-30 s (keep well clear of filter-induced correlations)
alpha, window_sizes, fluctuations, _ = DFA(envelope, fs, fit_interval=[3, 30], compute_interval=[0.1, 30])
print(alpha.round(2))

Signals have channels along the first dimension and time along the second, the opposite of NBT. On this random test signal the 23 values range from about 0.45 to 0.64. For a whole frequency range at once, crosci.biomarkers.compute_spectrum_biomarkers filters, extracts envelopes and chooses a fitting range per frequency band (Diachenko et al., 2024).


Computing DFA in MATLAB with NBT#

We show how to perform detrended fluctuation analysis in MATLAB using NBT. In this example, we compute DFA in the alpha frequency band (8–13 Hz) with a sampling frequency of 250 Hz.

If you do not have data, generate a test signal:

Signal = randn(300*250, 23);

This generates a 5-minute (300 seconds) signal with 23 channels.

1. Removing artefacts#

NBT has several functions for artefact removal. Large-amplitude transient artefacts will strongly influence the temporal structure of the signal and should be cut away. Important: the time series should be stitched together after cutting artefact segments. Signals in NBT have time along the 1st dimension and channels along the 2nd dimension.

2. Filter the signal and extract the amplitude envelope#

Use nbt_GetAmplitudeEnvelope to filter the signal and extract the amplitude envelope:

SignalInfo = nbt_Info;
SignalInfo.converted_sample_frequency = 250;
AmplitudeEnvelope = nbt_GetAmplitudeEnvelope(Signal, SignalInfo, 8, 13, 2/8);

The nbt_Info function defines an NBT info object containing information about your signal. The last parameter 2/8 is the filter order (in seconds), set so that at least two oscillation cycles are covered by the filter window.

3. Perform DFA#

Calculate the DFA exponent and plot the fluctuation function:

[DFAobject, DFA_exp] = nbt_doDFA(AmplitudeEnvelope, SignalInfo, [1 15], [0.8 25], 0.5, 1, 1, []);

Parameters: Signal, SignalInfo, FitInterval (time range for fitting), CalcInterval (time range for calculation), DFA_Overlap (window overlap, here 50%), DFA_Plot, ChannelToPlot, and res_logbin (resolution of logarithmic binning, default 10).

After calculation, find the DFA values for all channels:

DFAobject.MarkerValues

Extended DFA tutorial#

Testing with random data#

First, verify that DFA yields α ≈ 0.5 for random data. Define a sampling frequency of 300 Hz and generate 20 minutes of random activity:

Fs = 300;
Signal = randn(20*60*Fs, 1);

SignalInfo = nbt_Info;
SignalInfo.converted_sample_frequency = Fs;
[DFAobject, DFA_exp] = nbt_doDFA(Signal, SignalInfo, [0.1 120], [0.08 1200], 0.5, 1, 1, []);

Rule of thumb: only estimate correlations up to time scales of 10% of the data length.

Did you get a DFA exponent close to 0.5?

The effect of filtering on correlations#

Long-range temporal correlations imply modulations on long time scales — but low-frequency fluctuations are typically removed during data acquisition with a high-pass filter around 0.1–1 Hz. Since we are interested in distinct oscillations, we use a bandpass filter and the Hilbert transform to extract the amplitude envelope of narrow-band oscillations.

However, bandpass filtering introduces autocorrelations at short time scales, even in random data. To see this, filter the random data at 8–13 Hz and compute DFA on the amplitude envelope:

highpass = 8;
lowpass = 13;
fir_order = 0.25;  % Filter order in seconds
[Data_filtered] = nbt_filter_fir(Signal, highpass, lowpass, Fs, 2/8);

Plot the filtered signal and its amplitude envelope:

figure
plot(Data_filtered, 'r')
hold on
plot(abs(hilbert(Data_filtered)), 'k')

You should see oscillations that fluctuate erratically in amplitude. Now compute DFA:

[DFAobject, DFA_exp] = nbt_doDFA(abs(hilbert(Data_filtered)), SignalInfo, [0.1 120], [0.08 1200], 0.5, 1, 1, []);

The DFA fluctuation function no longer increases linearly — the correlations do not decay according to a simple power law across all time scales. To find the time scales not affected by filter-induced correlations, fit separately to short and long ranges:

Short-range:

[DFAobject, DFA_exp] = nbt_doDFA(abs(hilbert(Data_filtered)), SignalInfo, [0.1 1], [0.08 1200], 0.5, 1, 1, []);

Long-range:

[DFAobject, DFA_exp] = nbt_doDFA(abs(hilbert(Data_filtered)), SignalInfo, [3 120], [0.08 1200], 0.5, 1, 1, []);

At time scales from 100 ms to 1 s, the amplitude fluctuations are strongly correlated (α > 1) — this is the filter artefact. At time scales of 3–120 s, correlations are absent (α ≈ 0.5), as expected for random data. For this specific 8–13 Hz filter, it is safe to interpret correlations on time scales longer than approximately 3 s as originating from the signal, not from filtering. This holds for the white-noise test. In real recordings with a narrow spectral peak, such as the alpha rhythm, the fluctuation function can deviate from a straight line, and depend on the signal-to-noise ratio, at time scales up to about 10 s (Nolte et al., 2019).

Applying DFA to real MEG data#

Now apply the same analysis to real MEG data. Download the sample MEG recording (MEG_data.mat, 2 MB). It contains 20 minutes of MEG sampled at 300 Hz from a right and a left sensorimotor channel (RSM, LSM), recorded while the median nerve was stimulated every 3 s (the stimulus pulses are in Trig), and empty-room recordings from the same channels (RSM_noise, LSM_noise). The signals are stored as row vectors, so transpose them to put time along the first dimension.

This is not a resting-state recording. Median-nerve stimulation modulates the amplitude of sensorimotor oscillations and attenuates their long-range temporal correlations (Linkenkaer-Hansen et al., 2004), so use the file to practise the method; for resting-state results use recordings without stimulation.

Use the fitting range you identified as having a proper null hypothesis, here 3–120 s:

load MEG_data.mat
RSM = RSM';                 % time along the 1st dimension
[RSM_filtered] = nbt_filter_fir(RSM, highpass, lowpass, Fs, 2/8);
[DFAobject, DFA_exp] = nbt_doDFA(abs(hilbert(RSM_filtered)), SignalInfo, [3 120], [0.08 1200], 0.5, 1, 1, []);

Long-range temporal correlations require a non-uniformity of fluctuations over time — a “patchy” time structure. Compare the filtered noise with the filtered MEG signal to see this visually.

Signal-to-noise ratio#

Check whether LRTC are present in laboratory noise by analysing the empty-room recording RSM_noise in the same way. Narrow-band filtered MEG noise should have close to no long-range temporal autocorrelations.

This raises a practical concern: if the signal-to-noise ratio is poor, can you reliably quantify the temporal correlations of the underlying physiological process? You can test this by adding amplified noise on top of neural data and checking whether the estimated DFA exponent changes.

This matters because: different conditions, subjects, or patient groups may have different signal-to-noise ratios. A change in the DFA exponent could potentially reflect different oscillation amplitudes rather than a true effect on LRTC. The influence of signal-to-noise ratio is a generic problem that also affects functional connectivity measures such as coherence and phase synchronisation (Bastos & Schoffelen, 2016).


Summary#

  • DFA quantifies long-range temporal correlations in time series
  • For uncorrelated data, α ≈ 0.5; for LRTC, 0.5 < α < 1
  • Bandpass filtering introduces short-timescale correlations — always verify the safe fitting range using filtered random data
  • Signal-to-noise ratio can bias DFA estimates — this must be controlled for when comparing across conditions or groups

References#

Bastos AM, Schoffelen JM (2016) A tutorial review of functional connectivity analysis methods and their interpretational pitfalls. Front Syst Neurosci 9:175. doi:10.3389/fnsys.2015.00175

Botcharova M, Farmer SF, Berthouze L (2014) Markers of criticality in phase synchronization. Front Syst Neurosci 8:176. doi:10.3389/fnsys.2014.00176

Bruining H, Hardstone R, Juarez-Martinez EL, et al. (2020) Measurement of excitation-inhibition ratio in autism spectrum disorder using critical brain dynamics. Sci Rep 10:9195. doi:10.1038/s41598-020-65500-4

Diachenko M, Sharma A, Smit DJA, Mansvelder HD, Bruining H, de Geus E, Avramiea AE, Linkenkaer-Hansen K (2024) Functional excitation-inhibition ratio indicates near-critical oscillations across frequencies. Imaging Neurosci 2. doi:10.1162/imag_a_00318

Hardstone R, Poil SS, Schiavone G, Jansen R, Nikulin VV, Mansvelder HD, Linkenkaer-Hansen K (2012) Detrended fluctuation analysis: A scale-free view on neuronal oscillations. Front Physiol 3:450. doi:10.3389/fphys.2012.00450

Linkenkaer-Hansen K, Nikulin VV, Palva JM, Kaila K, Ilmoniemi RJ (2004) Stimulus-induced change in long-range temporal correlations and scaling behaviour of sensorimotor oscillations. Eur J Neurosci 19:203. doi:10.1111/j.1460-9568.2004.03116.x

Linkenkaer-Hansen K, Nikouline VV, Palva JM, Ilmoniemi RJ (2001) Long-range temporal correlations and scaling behavior in human brain oscillations. J Neurosci 21:1370–1377. doi:10.1523/JNEUROSCI.21-04-01370.2001

Montez T, Poil SS, Jones BF, et al. (2009) Altered temporal correlations in parietal alpha and prefrontal theta oscillations in early-stage Alzheimer disease. PNAS 106:1614–1619. doi:10.1073/pnas.0811699106

Monto S, Vanhatalo S, Holmes MD, Palva JM (2007) Epileptogenic neocortical networks are revealed by abnormal temporal dynamics in seizure-free subdural EEG. Cereb Cortex 17:1386–1393. doi:10.1093/cercor/bhl049

Nolte G, Aburidi M, Engel AK (2019) Robust calculation of slopes in detrended fluctuation analysis and its application to envelopes of human alpha rhythms. Sci Rep 9:6339. doi:10.1038/s41598-019-42732-7

Peng CK, Havlin S, Stanley HE, Goldberger AL (1995) Quantification of scaling exponents and crossover phenomena in nonstationary heartbeat time series. Chaos 5:82–87. doi:10.1063/1.166141

Poil SS, Jansen R, van Aerde K, et al. (2011) Fast network oscillations in vitro exhibit a slow decay of temporal auto-correlations. Eur J Neurosci 34:394–403. doi:10.1111/j.1460-9568.2011.07748.x