Main Content

weightingFilter

Frequency-weighted filter

Description

The weightingFilter System object™ performs frequency-weighted filtering independently across each input channel.

To perform frequency-weighted filtering:

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

weightFilt = weightingFilter creates a System object, weightFilt, that performs frequency-weighted filtering independently across each input channel.

weightFilt = weightingFilter(weightType) sets the Method property to weightType.

weightFilt = weightingFilter(weightType,Fs) sets the SampleRate property to Fs.

weightFilt = weightingFilter(___,Name,Value) sets each property Name to the specified Value. Unspecified properties have default values.

Example: weightFilt = weightingFilter('C-weighting','SampleRate',96000) creates a C-weighting filter with a sample rate of 96,000 Hz.

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.

Type of weighting, specified as 'A-weighting', 'C-weighting', or 'K-weighting'. See Algorithms for more information.

Tunable: No

Data Types: char | string

Input sample rate in Hz, specified as a positive scalar.

Tunable: Yes

Data Types: single | double

Usage

Description

audioOut = weightFilt(audioIn) applies frequency-weighted filtering to the input signal, audioIn, and returns the filtered signal, audioOut. The type of filtering is specified by the algorithm and properties of the weightingFilter System object, weightFilt.

example

Input Arguments

expand all

Audio input to the weighting filter, specified as a matrix. The columns of the matrix are treated as independent audio channels.

Data Types: single | double

Output Arguments

expand all

Audio output from the weighting filter, returned as a matrix the same size as audioIn.

Data Types: single | double

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

visualizeVisualize and validate filter response
getFilterReturn filter object with design parameters set
createAudioPluginClassCreate audio plugin class that implements functionality of System object
isStandardCompliantVerify filter design is IEC 61672-1:2002 compliant
cloneCreate duplicate System object
isLockedDetermine if System object is in use
releaseRelease resources and allow changes to System object property values and input characteristics
resetReset internal states of System object
stepRun System object algorithm

Note

weightingFilter supports additional filter analysis functions. See Compare and Analyze Weighting Types for details.

Examples

collapse all

Check the compliance status of filter designs and visualize them.

Create an A-weighting filter with a 22.5 kHz sample rate. Verify that the filter is standard compliant and visualize the filter design.

aWeight = weightingFilter('A-weighting','SampleRate',22500);
complianceStatus = isStandardCompliant(aWeight,'class 1')
complianceStatus = logical
   0

visualize(aWeight,'class 1')

Change your A-weighting filter sample rate to 44.1 kHz. Verify that the filter is standard compliant and visualize the filter design.

aWeight.SampleRate = 44100;

complianceStatus = isStandardCompliant(aWeight,'class 1')
complianceStatus = logical
   1

Use the weightingFilter System object™ to design an A-weighted filter, and then process an audio signal using your frequency-weighted filter design.

Create a dsp.AudioFileReader System object.

samplesPerFrame = 1024;
reader = dsp.AudioFileReader(Filename="RockGuitar-16-44p1-stereo-72secs.wav", ...
    SamplesPerFrame=samplesPerFrame, ...
    PlayCount=Inf);

Create a weightingFilter System object. Use the sample rate of the reader as the sample rate of the weighting filter.

Fs = reader.SampleRate;
weightFilt = weightingFilter("A-weighting",Fs);

Create a spectrum analyzer to visualize the original audio signal and the audio signal after frequency-weighted filtering.

scope = spectrumAnalyzer( ...
    SampleRate=Fs, ...
    PlotAsTwoSidedSpectrum=false, ...
    FrequencyScale="log", ...
    Title="A-Weighted Filtering", ...
    ShowLegend=true, ...
    ChannelNames=["Original signal","Filtered signal"]);

Process the audio signal in an audio stream loop. Visualize the filtered audio and the original audio. As a best practice, release the System objects when complete.

tic
while toc < 20
    x = reader();
    y = weightFilt(x);
    scope([x(:,1),y(:,1)])
end

release(weightFilt)
release(reader)
release(scope)

Compare the A-weighted, C-weighted, and K-weighted filtering of an engine sound.

Create an A-weighting filter, a C-weighting filter, and a K-weighting filter. Compare and analyze the filters.

wF{1} = weightingFilter;
wF{2} = weightingFilter('C-weighting');
wF{3} = weightingFilter('K-weighting');

fa = filterAnalyzer(wF{1},wF{2},wF{3},SampleRates=wF{1}.SampleRate, ...
    FrequencyScale="log");
setLegendStrings(fa,["A-weighting","C-weighting","K-weighting"])

The weightingFilter object supports several filter analysis methods. For more information, use help at the command line:

help weightingFilter.helpFilterAnalysis
    The following analysis methods are available for discrete-time filter System objects:
 
    filterAnalyzer -  Filter Analyzer app
 
    info         -  Filter information
    freqz        -  Frequency response
    phasez       -  Phase response
    zerophase    -  Zero-phase response
    grpdelay     -  Group delay response
    phasedelay   -  Phase delay response
    impz         -  Impulse response
    impzlength   -  Length of impulse response
    stepz        -  Step response
    zplane       -  Pole/zero plot
    cost         -  Cost estimate for implementation of the filter System object
    measure      -  Measure characteristics of the frequency response
 
    outputDelay  -  Output delay value
    order        -  Filter order
    coeffs       -  Filter coefficients in a structure
    firtype      -  Determine the type (1-4) of a linear phase FIR filter System object
    tf           -  Convert to transfer function
    zpk          -  Convert to zero-pole-gain
    ss           -  Convert to state space representation
 
    isallpass    -  Verify if filter System object is allpass
    isfir        -  Verify if filter System object is FIR
    islinphase   -  Verify if filter System object is linear phase
    ismaxphase   -  Verify if filter System object is maximum phase
    isminphase   -  Verify if filter System object is minimum phase
    isreal       -  Verify if filter System object is minimum real
    issos        -  Verify if filter System object is in second-order sections form
    isstable     -  Verify if filter System object is stable
 
    realizemdl   -  Filter realization (Simulink diagram)
 
    specifyall   -  Fully specify fixed-point filter System object settings
 
    cascade      -  Create a dsp.FilterCascade System object
    parallel     -  Create a dsp.ParallelFilter System object
 
    Second-order sections:
 
    scale        -  Scale second-order sections of BiquadFilter System object
    scalecheck   -  Check scaling of BiquadFilter System object
    reorder      -  Reorder second-order sections of BiquadFilter System object
    cumsec       -  Cumulative second-order section of BiquadFilter System object
    scaleopts    -  Create an options object for second-order section scaling
    sos          -  Convert to second-order-sections (for IIRFilter System objects only)
 
    Fixed-Point (Fixed-Point Designer Required):
 
    freqrespest  -  Frequency response estimate via filtering
    freqrespopts -  Create an options object for frequency response estimate
    noisepsd     -  Power spectral density of filter output due to roundoff noise
    noisepsdopts -  Create an options object for output noise PSD computation
 
    Multirate Analysis:
 
    freqzmr                  - DTFT of the impulse response
    polyphase                - Polyphase decomposition of multirate filter System object
    gain (CIC decimator)     - Gain of CIC decimator filter System object
    gain (CIC interpolator)  - Gain of CIC interpolator filter System object
 
    For decimator, interpolator, or rate change filter System objects
    the analysis tools perform computations relative to the rate at
    which the filter is running. If a sampling frequency is specified,
    it is assumed that the filter is running at that rate.

Help for weightingFilter.helpFilterAnalysis is inherited from superclass dsp.internal.FilterAnalysis

Create a dsp.AudioFileReader and specify a sound file. Create an audioDeviceWriter with default properties. In an audio stream loop, play the white noise, and then listen to it filtered through the A-weighted, C-weighted, and K-weighted filters, successively.

fileReader = dsp.AudioFileReader('Engine-16-44p1-stereo-20sec.wav');
deviceWriter = audioDeviceWriter('SampleRate',fileReader.SampleRate);

fprintf('No filtering...')
No filtering...
for i = 1:400
    x = fileReader();
    if i==100
        index = 1;
        fprintf('A-weighted filtering...')
    elseif i==200
        index = 2;
        fprintf('C-weighted filtering...')
    elseif i==300
        index = 3;
        fprintf('K-weighted filtering...\n')
    end
    if i>99
        y = wF{index}(x);
    else
        y = x;
    end
    deviceWriter(y);
end
A-weighted filtering...
C-weighted filtering...
K-weighted filtering...

As a best practice, release your objects once done.

release(deviceWriter)
release(fileReader)

The weightingFilter object uses second-order sections (SOS) for filtering. To extract the weighting filter design, use getFilter to return a dsp.SOSFilter object.

Use weightingFilter to create C-weighted and A-weighted filter objects. Use getFilter to return corresponding dsp.SOSFilter objects.

cFilt = weightingFilter('C-weighting');
aFilt = weightingFilter('A-weighting');
cSOSFilter = getFilter(cFilt);
aSOSFilter = getFilter(aFilt);

Create an audio file reader and audio device writer for audio input/output. Use the sample rate of your reader as the sample rate of your writer.

fileReader = dsp.AudioFileReader('JetAirplane-16-11p025-mono-16secs.wav');
deviceWriter = audioDeviceWriter('SampleRate',fileReader.SampleRate);

In an audio stream loop, play the unfiltered signal. Release your file reader so that the next time you call it, it reads from the beginning of the file.

tic
while toc<8
    x = fileReader();
    deviceWriter(x);
end
release(fileReader)

Play the signal processed by the A-weighted filter. Then play the signal processed by the C-weighted filter. Cache the power in each frame of the original and filtered signals for analysis. As a best practice, release your file reader and device writer once complete.

y = [];
count = 1;
tic
while ~isDone(fileReader)
    x = fileReader();
    aFiltered = aSOSFilter(x);
    cFiltered = cSOSFilter(x);
    if toc>8
        deviceWriter(cFiltered);
    else
        deviceWriter(aFiltered);
    end
    xPower(count) = var(x);
    aPower(count) = var(aFiltered);
    cPower(count) = var(cFiltered);
    y = [y;x];
    count = count+1;
end

release(fileReader)
release(deviceWriter)

Plot the power of the original signal, the A-weighted signal, and the C-weighted signal over time.

subplot(2,1,1)
spectrogram(y,512,256,4096,fileReader.SampleRate,'yaxis')
title('Original Signal')

subplot(2,1,2)
t = linspace(0,16.3468,count-1);
plot(t,xPower,'r',t,aPower,'b',t,cPower,'g')
legend('Original Signal','A-Weighted','C-Weighted')
xlabel('Time (s)')
ylabel('Power')

Figure contains 2 axes objects. Axes object 1 with title Original Signal, xlabel Time (s), ylabel Frequency (kHz) contains an object of type image. Axes object 2 with xlabel Time (s), ylabel Power contains 3 objects of type line. These objects represent Original Signal, A-Weighted, C-Weighted.

Algorithms

expand all

References

[1] Acoustical Society of America. Design Response of Weighting Networks for Acoustical Measurements. ANSI S1.42-2001. New York, NY: American National Standards Institute, 2001.

[2] International Electrotechnical Commission. Electroacoustics Sound Level Meters Part 1: Specifications. First Edition. IEC 61672-1. 2002–2005.

[3] International Telecommunication Union. Algorithms to measure audio programme loudness and true-peak audio level. ITU-R BS.1770-4. 2015.

[4] Mansbridge, Stuart, Saoirse Finn, and Joshua D. Reiss. "Implementation and Evaluation of Autonomous Multi-track Fader Control." Paper presented at the 132nd Audio Engineering Society Convention, Budapest, Hungary, 2012.

Extended Capabilities

Version History

Introduced in R2016b