detrend
result = detrend(x, [order=1])
Input: x, order · Output: result
What it is
Subtracts a least-squares polynomial trend from x, a length-N number vector. order is an optional positional integer: 0 removes the mean, 1 (default) a linear drift, 2 a quadratic bow.
Overloads
One call shape — this function is not overloaded.
| Code | Input | Output | Description |
result = detrend(x, [order=1]) | x number or vectorSubtracts a least-squares polynomial trend from x, a length-N number vector.order optional (default 1)order is an optional positional integer: 0 removes the mean, 1 (default) a linear drift, 2 a quadratic bow. | result vector | Returns a length-N vector. For baseline wander. |
Examples
From the documentation, and run by the build -- the output and the figure below are what the engine actually produced. Simplest first.
print(detrend([1, 2, nan, 4], 0)) # [NaN, NaN, NaN, NaN]
output
[NaN, NaN, NaN, NaN]
from noise
fs = 1000
n = 500
t = (0 to n - 1) / fs
clean = sin(2 * pi * 7 * t)
spike = 5 * impulse(n, index = 200)
corrupted = clean + spike + 0.01 * (0 to n - 1) # a spike, plus baseline drift
fixed = medfilt(corrupted, 5) # the spike
flat = detrend(fixed, 1) # the ramp
sg = savgol(flat, 11, 2) # a final polish, shape-preserving
sm = smooth(flat, 11) # same thing, one word (default method is savgol)
print("after cleanup: {measure_snr(clean, sg):.2f} dB (savgol), {measure_snr(clean, sm):.2f} dB (smooth)")
output
after cleanup: 17.81 dB (savgol), 17.81 dB (smooth)
from noise
How it works
detrend(x, [order]) — remove a least-squares polynomial trend. 0 the mean, 1 a linear drift, 2 a bow. Usually the first step of an analysis, because baseline wander is what brown noise looks like after the fact.
From the note above this builtin in the interpreter, where the reasoning was written down as it was built.