Main Content

dsp.MovingStandardDeviation

R2026b

Moving standard deviation

Description

The dsp.MovingStandardDeviation System object™ computes the moving standard deviation of the input signal along each channel, independently over time. The object uses either the sliding window method or the exponential weighting method to compute the moving standard deviation. In the sliding window method, a window of specified length is moved over the data, sample by sample, and the object computes the standard deviation over the data in the window. In the exponential weighting method, the object computes the exponentially weighted moving variance, and takes the square root.

You can make the window length tunable by setting the EnableTunableWindowLength property to true. In this mode, use the TunableWindowLength property to change the window length even after you pass some data to the object and the object is locked. The MaxWindowLength property specifies the maximum allowed window length. (since R2026b)

For more details, see Algorithms.

The dsp.MovingStandardDeviation object and the movstd function both compute the moving standard deviation of the input signal. However, the object can process large streams of real-time data and handle system states automatically. The function performs one-time computations on data that is readily available and cannot handle system states. For a comparison between the two, see System Objects vs MATLAB Functions.

To compute the moving standard deviation of the input:

  1. Create the dsp.MovingStandardDeviation object and set its properties.

  2. Call the object with arguments, as if it were a function.

To learn more about how System objects work, see What Are System Objects?

Creation

Description

MovStd = dsp.MovingStandardDeviation returns a moving standard deviation object, MovStd, using the default properties.

MovStd = dsp.MovingStandardDeviation(Len) sets the WindowLength property to Len.

example

MovStd = dsp.MovingStandardDeviation(Len,Overlap) sets the WindowLength property to Len and the OverlapLength property to Overlap.

MovStd = dsp.MovingStandardDeviation(PropertyName=Value) specifies additional properties using Name=Value pairs. For example, to specify an exponential weighting factor of 0.88, set ForgettingFactor to 0.88.

example

Properties

expand all

Unless otherwise indicated, properties are nontunable, which means you cannot change their values after calling the object. Objects lock when you call them, and the release function unlocks them.

If a property is tunable, you can change its value at any time.

For more information on changing property values, see System Design in MATLAB Using System Objects.

  • "Sliding window" — A window of length specified by SpecifyWindowLength is moved over the input data along each channel. For every sample the window moves by, the object computes the standard deviation over the data in the window.

  • "Exponential weighting" — The object computes the exponentially weighted moving variance, and takes the square root.

For more details on these methods, see Algorithms.

Flag to specify a window length, specified as a scalar boolean.

  • true — The length of the sliding window is equal to the value you specify in the WindowLength property.

  • false — The length of the sliding window is infinite. In this mode, the standard deviation is computed using the current sample and all the past samples.

Dependencies

This property applies when you set Method to "Sliding window".

Since R2026b

Option to enable tunable window length, specified as a scalar boolean.

  • true — The window length is tunable, that is, you can change its value even after you pass some data to the object and the object is locked. Use the TunableWindowLength property to specify the window length.

  • false — The window length is not tunable. Use the WindowLength property to specify a fixed window length.

Dependencies

This property applies when you set:

  • Method to "Sliding window"

  • SpecifyWindowLength to true

Since R2026b

Tunable sliding window length in samples, specified as a positive integer in the range [1, MaxWindowLength]. You can change the value of this property even when the object is locked.

When you set AutoAdjustInvalidWindowLength to true, the object adjusts invalid values and issues a warning:

  • If the tunable window length value is greater than MaxWindowLength, the object uses MaxWindowLength.

  • If the tunable window length value is less than 1, the object uses 1.

  • If the tunable window length value is not an integer, the object uses the floored value.

When you set AutoAdjustInvalidWindowLength to false, the object throws an error for invalid values.

Tunable: Yes

Dependencies

This property applies when you set:

  • Method to "Sliding window"

  • SpecifyWindowLength to true

  • EnableTunableWindowLength to true

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Since R2026b

Maximum value of the tunable window length, specified as a positive integer. The TunableWindowLength property must be less than or equal to this value.

Dependencies

This property applies when you set:

  • Method to "Sliding window"

  • SpecifyWindowLength to true

  • EnableTunableWindowLength to true

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Since R2026b

Option to automatically adjust invalid window length values, specified as a scalar boolean.

  • true — The object adjusts invalid TunableWindowLength values and issues a warning.

    • If the tunable window length value is greater than MaxWindowLength, the object sets its value to MaxWindowLength.

    • If the tunable window length value is less than 1, the object sets its value to 1.

    • If the tunable window length value is not an integer, the object uses the floored value.

  • false — The object throws an error when the tunable window length value is invalid.

Dependencies

This property applies when you set:

  • Method to "Sliding window"

  • SpecifyWindowLength to true

  • EnableTunableWindowLength to true

Length of the sliding window in samples, specified as a positive integer. You cannot tune the value of this property after the object is locked. To tune the window length, set the EnableTunableWindowLength property to true.

Dependencies

This property applies when you set:

  • Method to "Sliding window"

  • SpecifyWindowLength to true

  • EnableTunableWindowLength to false

(since R2026b)

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Overlap length between sliding windows, specified as a nonnegative integer. The value of overlap length varies in the range [0, WindowLength − 1]. If not specified, the overlap length is WindowLength − 1.

Dependencies

This property applies when you set:

  • Method to "Sliding window"

  • SpecifyWindowLength to true

  • EnableTunableWindowLength to false

(since R2026b)

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Exponential weighting factor, specified as a nonnegative real scalar in the range [0,1]. A forgetting factor of 0.9 gives more weight to the older data than does a forgetting factor of 0.1. A forgetting factor of 1.0 indicates infinite memory and all the past samples are given an equal weight. A forgetting factor of 0 indicates no memory and the past samples have no weight on the current computation.

Since this property is tunable, you can change its value even when the object is locked.

Tunable: Yes

Dependencies

This property applies when you set Method to "Exponential weighting".

Data Types: single | double

Usage

Description

y = movStd(x) computes the moving standard deviation of the input signal, x, using either the sliding window method or exponential weighting method.

example

Input Arguments

expand all

Data input, specified as a vector or a matrix. If x is a matrix, each column is treated as an independent channel. The moving standard deviation is computed along each channel.

The object accepts variable-size inputs. Once the object is locked, you can change the size of each input channel, but you cannot change the number of channels.

Data Types: single | double
Complex Number Support: Yes

Output Arguments

expand all

Moving standard deviation of the input signal, returned as a vector or a matrix.

When you input a signal of size m-by-n to the object, and if you set Method to "Sliding window" and SpecifyWindowLength to true, the output has an upper bound size of ceil(m/hop size)-by-n. Hop size is window length − overlap length. In other cases, the output has a size of m-by-n.

When you generate code from this object, the variable-size behavior of the output in the generated code depends on the input frame length and whether the size of the input signal is fixed or variable. For more details, see Code Generation.

Data Types: single | double
Complex Number Support: Yes

Object Functions

To use an object function, specify the System object as the first input argument. For example, to release system resources of a System object named obj, use this syntax:

release(obj)

expand all

stepRun System object algorithm
releaseRelease resources and allow changes to System object property values and input characteristics
resetReset internal states of System object

Examples

collapse all

Compute the moving standard deviation of a noisy square wave signal with varying amplitude using the dsp.MovingStandardDeviation object.

Initialization

Set up movstdWindow, movstdWindow_overlap, and movstdExp objects. movstdWindow uses the sliding window method with a window length of 800 samples and a default overlap length of 799 samples, which is one sample less than the specified window length. movstdWindow_overlap uses a window length of 800 samples and an overlap length of 700 samples. movstdExp uses the exponentially weighting method with a forgetting factor of 0.999.

Create a time scope for viewing the output.

FrameLength = 100;
Fs = 100;
movstdWindow = dsp.MovingStandardDeviation(800);
movstdWindow_overlap = dsp.MovingStandardDeviation(800,700);
movstdExp = dsp.MovingStandardDeviation(...
    Method="Exponential weighting",...
    ForgettingFactor=0.999);
scope  = timescope(SampleRate=[Fs,Fs,Fs/(800-700),Fs],...
    TimeSpanOverrunAction="Scroll",...
    TimeSpanSource="Property",...
    TimeSpan=1000,...
    ShowGrid=true,...
    BufferLength=1e7,...
    YLimits=[0 3e-2]);
title = "Moving Standard Deviation";
scope.Title = title;
scope.ChannelNames = {"Original Signal",...
    "Sliding window of 800 samples with default overlap",...
    "Sliding window of 800 samples with an overlap of 700 samples",...
    "Exponential weighting with forgetting factor of 0.999"};

Compute the Standard Deviation

Generate a noisy square wave signal. Vary the amplitude of the square wave after a given number of frames. Apply the sliding window method and the exponential weighting method to this signal. The actual standard deviation is sqrt(np). The object uses this value while adding noise to the data. Compare the actual standard deviation with the computed standard deviation in the time scope.

count = 1;
noisepower = 1e-4 * [1 2 3 4];
for index = 1:length(noisepower)
    np = noisepower(index);
    yexp = sqrt(np)*ones(FrameLength,1);
    for i = 1:250
        x = sqrt(np) * randn(FrameLength,1);
        y1 = movstdWindow(x);
        y2 = movstdWindow_overlap(x);
        y3 = movstdExp(x);
        scope(yexp,y1,y2,y3);
    end
end

Since R2026b

Compute the moving standard deviation of a noisy sinusoidal signal and adapt the window length based on the noise level. Use a longer window when the noise is light for a stable estimate and a shorter window when the noise is heavy for faster tracking.

Create Input Signal

Create a sine wave signal with a frequency of 2 Hz to simulate a baseline sensor reading. Set the sampling rate to 1000 Hz and the frame size to 256 samples.

Fs = 1000;
frameSize = 256;
numFrames = 40;
sine = dsp.SineWave(Frequency=2,SampleRate=Fs,...
    SamplesPerFrame=frameSize);

Create Moving Standard Deviation Object

Create a dsp.MovingStandardDeviation object with tunable window length enabled. Set the maximum window length to 50 and the initial tunable window length to 40 (long window for stable baseline). Enable auto-adjustment to handle edge cases.

movStd = dsp.MovingStandardDeviation(EnableTunableWindowLength=true,...
    TunableWindowLength=40,...
    MaxWindowLength=50,...
    AutoAdjustInvalidWindowLength=true)
movStd = 
  dsp.MovingStandardDeviation with properties:

                           Method: 'Sliding window'
              SpecifyWindowLength: true
        EnableTunableWindowLength: true
              TunableWindowLength: 40
                  MaxWindowLength: 50
    AutoAdjustInvalidWindowLength: true

Create a timescope object to view the input signal, moving standard deviation output, and the adaptive window length.

scope = timescope(SampleRate=Fs,...
    TimeSpanSource="property",TimeSpan=numFrames*frameSize/Fs,...
    TimeSpanOverrunAction="Scroll",...
    ShowGrid=true,...
    LayoutDimensions=[3 1],...
    NumInputPorts=3, ...
    ChannelNames=["Input Signal with Anomalies",...
    "Moving Standard Deviation","Adaptive Window Length"]);
scope.ActiveDisplay = 1;
scope.YLimits = [-4 4];
scope.ActiveDisplay = 2;
scope.YLimits = [0 2.5];
scope.ActiveDisplay = 3;
scope.YLimits = [0 55];

Apply Adaptive Anomaly Detection

Add Gaussian noise whose power grows linearly over time. At each frame, set the window length inversely proportional to the noise power. A shorter window produces a standard deviation estimate that reacts quickly to sudden changes, while a longer window produces a smoother, more stable estimate.

threshold = 0.5;
wl = 40;
for idx = 1:numFrames
    x = sine();

    % Inject anomaly bursts at specific frames
    if mod(idx,10) >= 7 && mod(idx,10) <= 9
        x = x + 2*randn(frameSize,1);
    else
        x = x + 0.1*randn(frameSize,1);
    end

    % Compute moving standard deviation
    movStd.TunableWindowLength = wl;
    y = movStd(x);

    % Adapt window length based on current standard deviation
    avgStd = mean(y);
    if avgStd > threshold
        wl = max(5,wl - 5);
    else
        wl = min(50,wl + 2);
    end

    % Display results
    scope(x,y,wl*ones(frameSize,1));
end

Since R2026b

Generate C code for a moving standard deviation computation with a tunable window length parameter. Verify that the window length appears as a tunable parameter in the generated code.

Create Entry-Point Function

Create an entry-point function that instantiates a dsp.MovingStandardDeviation object with tunable window length enabled. The function accepts a data input and a tunable window length value.

type movingStdTunableWL.m
function y = movingStdTunableWL(x,wl) %#codegen
%movingStdTunableWL Moving standard deviation with tunable window length
%   y = movingStdTunableWL(x,wl) computes the moving standard deviation of
%   the input x using a window length that can be changed at runtime.

persistent movStd
if isempty(movStd)
    movStd = dsp.MovingStandardDeviation(EnableTunableWindowLength=true,...
        MaxWindowLength=31,...
        AutoAdjustInvalidWindowLength=true);
end

movStd.TunableWindowLength = wl;
y = movStd(x);
end

Generate C Code

Generate C code for the entry-point function using codegen. Specify the input data as a 256-by-1 column vector of doubles and the window length as a scalar double.

codegen movingStdTunableWL -args {zeros(256,1),0} -config:lib -report
Code generation successful: View report

Verify Tunable Parameter in Generated Code

Inspect the generated code to verify that TunableWindowLength appears as a parameter that can be changed at runtime without regenerating code.

The generated code contains the TunableWindowLength field in the persistent object state, confirming that you can change the window length at runtime in the deployed code.

Algorithms

expand all

References

[1] Bodenham, Dean. “Adaptive Filtering and Change Detection for Streaming Data.” PH.D. Thesis. Imperial College, London, 2012.

Extended Capabilities

expand all

Version History

Introduced in R2016b

expand all