Main Content

dsp.ColoredNoise

Generate colored noise signal

Description

The dsp.ColoredNoise System object™ generates a colored noise signal with a power spectral density (PSD) of 1/|f|α over its entire frequency range. The inverse frequency power, α, can be any value in the interval [-2 2]. The type of colored noise the object generates depends on the Color you choose. When you set Color to 'custom', you can specify the power density of the noise through the InverseFrequencyPower property.

This object uses the default MATLAB® random stream, RandStream. Reset the default stream for repeatable simulations.

To generate colored noise signal:

  1. Create the dsp.ColoredNoise 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

cn = dsp.ColoredNoise creates a colored noise object, cn, that outputs a noise signal one sample or frame at a time, with a 1/|f|α spectral characteristic over its entire frequency range. Typical values for α are α = 1 (pink noise) and α = 2 (brownian noise).

example

cn = dsp.ColoredNoise(Name=Value) creates a colored noise object with each specified property set to the specified value. Enclose each property name in single quotes.

Example: dsp.ColoredNoise(Color='pink');

example

cn = dsp.ColoredNoise(pow,samp,numChan,Name=Value) creates a colored noise object with the InverseFrequencyPower property set to pow, the SamplesPerFrame property set to samp, and the NumChannels property set to numChan.

Example: dsp.ColoredNoise(1,44.1e3,1,OutputDataType='single');

example

cn = dsp.ColoredNoise(color,samp,numChan,Name=Value) creates a colored noise object with the Color property set to color, the SamplesPerFrame property set to samp, and the NumChannels property set to numChan.

Example: dsp.ColoredNoise('pink',1024,2,OutputDataType='single');

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.

Noise color, specified as one of the following. Each color is associated with a specific inverse frequency power of the generated noise sequence.

  • 'pink' –– The inverse frequency power α equals 1.

  • 'white' –– α = 0.

  • 'brown' –– α = 2. Also known as red or Brownian noise.

  • 'blue' –– α = -1. Also known as azure noise.

  • 'purple' –– α = -2. Also known as violet noise.

  • 'custom' –– For noise with a custom inverse frequency power, α equals the value of the InverseFrequencyPower property.

    InverseFrequencyPower α can be any value in the interval [-2,2].

Data Types: char | string

Inverse frequency power α, specified as a real scalar in the interval [-2 2]. The inverse exponent defines the PSD of the random process as 1/|f|α. Values of InverseFrequencyPower greater than 0 generate lowpass noise with a singularity (pole) at f = 0. These processes exhibit long memory. Values of InverseFrequencyPower less than 0 generate highpass noise with increments that are negatively correlated. These processes are referred to as anti-persistent. Special cases include:

  • 1 –– Pink noise

  • 2 –– Brown, red, or Brownian noise

  • 0 –– White noise process with a flat PSD

  • -1 –– Blue or azure noise

  • -2 –– Purple of violet noise

In a log-log plot of power as a function of frequency, processes generated by this object exhibit an approximate linear relationship with slope equal to –α.

Dependencies

This property applies only when you set Color to 'custom'.

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

Source of the number of samples per frame, specified as 'Property' or 'Input port'.

Data Types: char | string

Number of samples per output channel, specified as a positive integer. This property determines the number of rows in the generated signal.

Dependencies

To enable this property, set SamplesPerFrameSource to 'Property'.

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

Maximum number of samples per frame, specified as a positive integer.

The value you specify in the MaxSamplesPerFrame property acts as an upper limit to the number of samples in each frame that the object generates. If you specify a value greater than MaxSamplesPerFrame, the number of samples in each frame that the object generates equals the value in the MaxSamplesPerFrame property.

Dependencies

To enable this property, set SamplesPerFrameSource to 'Input port'.

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

Number of output channels, specified as an integer. This property determines the number of columns of the generated signal.

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

Source of the random number stream, specified as one of the following:

  • 'Global stream' –– The current global random number stream is used for normally distributed random number generation.

  • 'mt19937ar with seed' –– The mt19937ar algorithm is used for normally distributed random number generation. The reset function reinitializes the random number stream to the value of the Seed property.

Data Types: char | string

Initial seed of mt19937ar random number stream generator algorithm, specified as a nonnegative integer. The reset function reinitializes the random number stream to the value of the Seed property.

Dependencies

This property applies only when you set the RandomStream property to 'mt19937ar with seed'.

Data Types: double

Specify the output to be bounded between +1 and −1, specified as:

  • true –– The internal random source that generates the noise is uniform instead of Gaussian, and a gain is applied so that the absolute maximum output never exceeds 1.

    If Color is set to 'white', there is no color filter applied to the output of the random source. The output is uniform noise of amplitude between +1 and −1. The output distribution of filtered noise (such as pink noise) is quasi-Gaussian.

    If Color is set to any other option, then a coloring filter is applied to the output of the random source, followed by a gain which ensures that the absolute maximum output never exceeds 1.

  • false –– The internal random source is Gaussian. The output is not bounded.

Data Types: logical

Output data type, specified as either 'double' or 'single'.

Data Types: char | string

Usage

Description

noiseOut = cn() outputs one sample or one frame of colored noise data.

example

noiseOut = cn(L) outputs one frame of colored noise data of length L, where L is a nonnegative integer.

This syntax applies only when you set SamplesPerFrameSource to 'Input port'.

example

Output Arguments

expand all

Colored noise output, returned as a vector or a matrix. The SamplesPerFrame, NumChannels, and the OutputDataType properties specify the size and data type of the output.

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

The output from this example shows that pink noise has approximately equal power in octave bands.

Generate a single-channel signal of pink noise that is 44,100 samples in length. Set the random number generator to the default settings for reproducible results.

pinkNoise = dsp.ColoredNoise(1,44.1e3,1)
pinkNoise = 
  dsp.ColoredNoise with properties:

                    Color: 'custom'
    InverseFrequencyPower: 1
            BoundedOutput: false
              NumChannels: 1
    SamplesPerFrameSource: 'Property'
          SamplesPerFrame: 44100
           OutputDataType: 'double'
             RandomStream: 'Global stream'

rng default;
x = pinkNoise();

Set the sample rate to 44.1 kHz. Measure the power in octave bands beginning with 100-200 Hz and ending with 6.400-12.8 kHz. Display the results in a table.

beginfreq = 100;
endfreq = 200;
count = 1;
freqinterval = zeros(7,2);
Pwr = zeros(7,1);
while(endfreq<=44.1e3/2)
    freqinterval(count,:) = [beginfreq endfreq];
    Pwr(count) = bandpower(x,44.1e3,[beginfreq endfreq]);
    beginfreq = endfreq;
    endfreq = 2*endfreq;
    count = count+1;
end
Pwr = Pwr(:);
table(freqinterval,Pwr)
ans=7×2 table
    freqinterval       Pwr  
    _____________    _______

     100      200    0.17549
     200      400    0.20313
     400      800     0.2438
     800     1600     0.2503
    1600     3200    0.25233
    3200     6400    0.26828
    6400    12800    0.25211

The pink noise has roughly equal power in octave bands.

Rerun the preceding code with 'InverseFrequencyPower' equal to 0, which generates a white noise signal. A white noise signal has a flat power spectral density, or equal power per unit frequency. Set the random number generator to the default settings for reproducible results.

whiteNoise = dsp.ColoredNoise(0,44.1e3,1);
rng default;
x = whiteNoise();

Set the sample rate to 44.1 kHz. Measure the power in octave bands beginning with 100-200 Hz and ending with 6.400-12.8 kHz. Display the results in a table.

beginfreq = 100;
endfreq = 200;
count = 1;
while(endfreq<=44.1e3/2)
    freqinterval(count,:) = [beginfreq endfreq];
    Pwr(count) = bandpower(x,44.1e3,[beginfreq endfreq]);
    beginfreq = endfreq;
    endfreq = 2*endfreq;
    count = count+1;
end
Pwr = Pwr(:);
table(freqinterval,Pwr)
ans=7×2 table
    freqinterval        Pwr   
    _____________    _________

     100      200    0.0031417
     200      400    0.0073833
     400      800     0.017421
     800     1600     0.035926
    1600     3200     0.071139
    3200     6400      0.15183
    6400    12800      0.28611

White noise has approximately equal power per unit frequency, so octave bands have an unequal distribution of power. Because the width of an octave band increases with increasing frequency, the power per octave band increases for white noise.

Generate a pink noise signal 2048 samples in length. The sample rate is 1 Hz. Obtain an estimate of the power spectral density using Welch's overlapped segment averaging.

cn = dsp.ColoredNoise('pink',SamplesPerFrame=2048);
x = cn();
Fs = 1;
[Pxx,F] = pwelch(x,hamming(128),[],[],Fs,'psd');

Construct the theoretical PSD of the pink noise process.

PSDPink = 1./F(2:end);

Display the Welch PSD estimate of the noise along with the theoretical PSD on a log-log plot. Plot the frequency axis with a base-2 logarithmic scale to clearly show the octaves. Plot the PSD estimate in dB, 10log10.

plot(log2(F(2:end)),10*log10(Pxx(2:end)))
hold on
plot(log2(F(2:end)),10*log10(PSDPink),'r',linewidth=2)
xlabel('log_2(Hz)')
ylabel('dB')
title('Pink Noise')
grid on
legend('PSD estimate','Theoretical pink noise PSD')
hold off

Figure contains an axes object. The axes object with title Pink Noise, xlabel log indexOf 2 baseline (Hz), ylabel dB contains 2 objects of type line. These objects represent PSD estimate, Theoretical pink noise PSD.

Generate two channels of Brownian noise by setting Color to 'brown' and NumChannels to 2. Specify the number of samples in each frame as an input while running the object algorithm.

cn = dsp.ColoredNoise('brown',SamplesPerFrameSource='Input port',...
    NumChannels=2)
cn = 
  dsp.ColoredNoise with properties:

                    Color: 'brown'
            BoundedOutput: false
              NumChannels: 2
    SamplesPerFrameSource: 'Input port'
       MaxSamplesPerFrame: 192000
           OutputDataType: 'double'
             RandomStream: 'Global stream'

x = cn(2048);
subplot(2,1,1)
plot(x(:,1)); title('Channel 1'); axis tight;
subplot(2,1,2)
plot(x(:,2)); title('Channel 2'); axis tight;

Figure contains 2 axes objects. Axes object 1 with title Channel 1 contains an object of type line. Axes object 2 with title Channel 2 contains an object of type line.

The sample rate is 1 Hz. Obtain Welch PSD estimates for both channels. The fourth argument of pwelch, NFFT, which is the number of FFT points, is empty. Hence, NFFT is set to 256. For even NFFT, The number of FFT points used to calculate the PSD estimate is (NFFT/2+1), which equals 129.

Fs = 1;
Pxx = zeros(129,size(x,2));
for nn = 1:size(x,2)
[Pxx(:,nn),F] = pwelch(x(:,nn),hamming(128),[],[],Fs,'psd');
end

Construct the theoretical PSD of a Brownian process. Plot the theoretical PSD along with both realizations on a log-log plot. Use a base-2 logarithmic scale for the frequency axis and plot the power spectral densities in dB.

PSDBrownian = 1./F(2:end).^2;
figure;
plot(log2(F(2:end)),10*log10(PSDBrownian),'k-.',linewidth=2);
hold on;
plot(log2(F(2:end)),10*log10(Pxx(2:end,:)));
xlabel('log_2(Hz)'); ylabel('dB');
grid on;
legend('Theoretical PSD','Channel 1', 'Channel 2');

Figure contains an axes object. The axes object with xlabel log indexOf 2 baseline (Hz), ylabel dB contains 3 objects of type line. These objects represent Theoretical PSD, Channel 1, Channel 2.

Note: The audioDeviceWriter System object™ is not supported in MATLAB Online.

This example shows how to stream in an audio file and add pink noise at a 0 dB signal-to-noise ratio (SNR). The example reads in frames of an audio file 1024 samples in length, measures the root mean square (RMS) value of the audio frame, and adds pink noise with the same RMS value as the audio frame.

Set up the System objects. Set 'SamplesPerFrame' for both the file reader and the colored noise generator to 1024 samples. Set Color to 'pink' to generate pink noise with a 1/|f| power spectral density.

N = 1024;
afr = dsp.AudioFileReader(Filename='speech_dft.mp3',...
    SamplesPerFrame=N);
adw = audioDeviceWriter(SampleRate=afr.SampleRate);
cn = dsp.ColoredNoise('pink',SamplesPerFrame=N);

Stream the audio file in 1024 samples at a time. Measure the signal RMS value for each frame, generate a frame of pink noise equal in length, and scale the RMS value of the pink noise to match the signal. Add the scaled noise to the signal and play the output.

while ~isDone(afr)
    audio = afr();
    speechRMS = rms(audio);
    noise = cn();
    noiseRMS = rms(noise);
    noise = noise*(speechRMS/noiseRMS);
    sigPlusNoise = audio+noise;
    adw(sigPlusNoise);   
end
release(afr);            
release(adw);

Generate two-channels of pink noise and compute the power density spectrum.

Set up the colored noise generator to generate two channels of pink noise with 1024 samples. Set up the spectrum analyzer to compute modified periodograms using a Hamming window and 50% overlap.

pinkNoise = dsp.ColoredNoise('pink',1024,2);
sa = spectrumAnalyzer(SpectrumType='power-density',...
    Method='welch',...
    AveragingMethod='exponential',...
    ForgettingFactor=0.95,...
    OverlapPercent=50,Window='hamming',...
    PlotAsTwoSidedSpectrum=false, ...
    FrequencyScale='log',YLimits=[-50 30]);

Run the simulation for 30 seconds.

tic
while toc < 30
    pink = pinkNoise();      
    sa(pink);
end

More About

expand all

Algorithms

The figure shows the overall process of generating the colored noise.

The random stream generator produces a stream of white noise that is either Gaussian or uniform in distribution. A coloring filter applied to the white noise generates colored noise with a power spectral density (PSD) function given by:

S(f)=L(f)|f|α

When α, the inverse frequency power, equals 0, no coloring filter is applied to the output of the random stream generator. If the bounded option is enabled, the output is uniform white noise with amplitude between +1 and −1. If the bounded output is not enabled, the output is a Gaussian white noise and the values are not bounded between +1 and −1. If α is set to any other value, then a coloring filter is applied to the output of the random stream generator. If the bounded output option is enabled, a gain g is applied to the output of the coloring filter to ensure that the absolute maximum output never exceeds 1.

For details on colored noise processes and how the value of α affects the PSD of the colored noise, see Colored Noise Processes.

When the inverse frequency power α is positive, the colored noise is generated using an auto regressive (AR) model of order 63. The AR coefficients are:

a0=1,ak=(k1α2)ak1k,k=1,2,,63

Pink and brown noises are special cases, which are generated from specially tuned SOS filters of orders 12 and 10, respectively. These filters are optimized for better performance.

When the inverse frequency power α is negative, the colored noise is generated using a moving average (MA) model of order 255. The MA coefficients are:

b0=1,bk=(k1+α2)bk1k,k=1,2,,255

Purple noise is generated from a first order filter, B = [1 −1].

The coloring filters applied (except pink, brown, and purple) are detailed on pp. 820–822 in [2].

References

[1] Beran, J., Y. Feng, S. Ghosh, and R. Kulik, Long-Memory Processes: Probabilistic Properties and Statistical Methods. NewYork: Springer, 2013.

[2] Kasdin, N.J. "Discrete Simulation of Colored Noise and Stochastic Processes and 1/fα Power Law Noise Generation." Proceedings of the IEEE®, Vol. 83, No. 5, 1995, pp. 802–827.

Extended Capabilities

Version History

Introduced in R2014a

expand all

See Also

Functions

Blocks