Main Content

zerocrossrate

Zero-crossing rate

Description

example

rate= zerocrossrate(x)returns the zero-crossing rate ofx. Ifxis a matrix, then the function analyzes each column as a separate channel and returns the zero-crossing rate as a row vector where each value corresponds to a channel.

example

rate= zerocrossrate(TT)returns the zero-crossing rate of the data stored in the MATLAB®timetableTT. IfTTcontains multiple channels, then the function analyzes each channel independently.

example

rate= zerocrossrate(___,Name,Value)specifies additional name-value arguments. Use this syntax with any of the input arguments in previous syntaxes.

example

[rate,count] = zerocrossrate(___)also returns the total number of crossings incount.

example

[rate,count,indices] = zerocrossrate(___)also returns logical indices at the signal locations where a crossing occurs.

zerocrossrate(___)with no output arguments plotsratealong they-axis and the corresponding window number along thex-axis. If the window length is equal to the full signal length, then the function plots the length of the window along thex-axis and the crossing rate in the middle of the window.

Examples

collapse all

Consider a vector of ones with alternating signs. Plot the data.

x = [1 -1 1 -1 1 -1 1 -1 1 -1]; plot(x)

Figure contains an axes object. The axes object contains an object of type line.

Compute the zero-crossing rate ofx.

r = zerocrossrate(x)
r = 0.9500

Use the third output argument to find the locations where the crossings occur. Plotxand the zero-crossing locations. The function returns an index at the next sample after a crossing, not necessarily the exact crossing location. The first sample is marked as a crossing point because the function considers the initial state ofxto be zero by default.

[~,~,indices] = zerocrossrate(x); plot(x) holdonplot(x(indices),'*') holdoff

Figure contains an axes object. The axes object contains 2 objects of type line.

Compute the zero-crossing rate ofxusing the comparison method. The rate differs from the value computed using the difference method.

rC = zerocrossrate(x,Method="comparison")
rC = 0.9000

Compute the zero-crossing rate ofxagain using the difference method and specify zero as positive. The rate is equal to the value computed using the comparison method.

rZ = zerocrossrate(x,ZeroPositive=1)
rZ = 0.9000

Now specify the initial state ofxas1. The rate is equal to the previous result.

rI = zerocrossrate(x,InitialState=1)
rI = 0.9000

Load a set of temperature readings in Celsius taken every hour at Logan Airport in Boston for the entire month of January, 2011. Create atimetableand use调整时间to aggregate the data into daily means.

loadbostempt = hours(1:24*31)'; TT = timetable(t,tempC); rTT = retime(TT,'daily','mean');

Count the number of days the temperature crosses the monthly average. Plot the data and include a horizontal line at the monthly average temperature to visualize where the crossings occur.

avg = mean(TT.tempC)
avg = -1.3007
[~,count] = zerocrossrate(rTT,Level=avg)
count = 9
plot(hours(rTT.t/24),rTT.tempC) yline(avg) xlabel('Time elapsed since January 1, 2011 (days)') ylabel('Average daily temperature (\circC)') axistight

Figure contains an axes object. The axes object contains 2 objects of type line, constantline.

Speech can be characterized as being voiced or unvoiced.Voicedspeech, such as vowel sounds, occurs when the vocal cords vibrate. Inunvoicedspeech, such as most consonant sounds, the vocal chords do not vibrate. You can use zero crossings to classify the voiced and unvoiced regions in an audio signal.

Load an audio signal into the MATLAB® workspace. The voice says, "Oak is strong, and also gives shade".

(y, fs) = audioread ("oak.m4a");% To hear, type soundsc(y,fs)

The signal is sampled at 44.1 kHz. Calculate the zero-crossing rate for 10 ms windows using the comparison method.

win = fs*0.01; rate = zerocrossrate(y,WindowLength=win,Method="comparison");

Plotrateto visualize the crossing rate for each segment. Voiced speech is expected to have a low crossing rate, while unvoiced speech is expected to have a high crossing rate.

plot(rate)

Figure contains an axes object. The axes object contains an object of type line.

Use a threshold of0.1to differentiate between voiced and unvoiced segments. Create asignalMaskobject that has two categories ("Unvoiced" and "Voiced") and plot the regions of interest (ROIs). Compare the regions of voiced and unvoiced speech to the location of each spoken word.

You can use Audio Toolbox™ speech-to-text functionality to extract words from an audio file. Load the labeled signal setlsfromSpeechTranscription.matinto the workspace. The labeled signal set contains the audio signal, ROI limits, and labels for each spoken word. For more information on labeling audio signals, seeLabel Spoken Words in Audio Signals. Display the spoken words on the plot.

h = 0.1; idu = find(rate > h); idu(1:2) = []; vi = [(idu-1) idu]*win; m = sigroi2binmask(vi,length(y)); mask = signalMask([m ~m],Categories=["Unvoiced""Voiced"],SampleRate=fs); plotsigroi(mask,y) loadSpeechTranscriptionln = getLabelNames(ls); v = getLabelValues(ls,1,ln); v.Value = categorical(v.Value,v.Value); RL = v.ROILimits; VL = v.Value; holdontext(mean(RL,2),-0.7*ones(size(VL)),VL,HorizontalAlignment="center",...FontSize=11,FontWeight="bold") holdoff

Figure contains an axes object. The axes object contains 10 objects of type line, text.

Load an audio file containing 15 seconds of acoustic guitar music. The sample rate is 44.1 kHz. To play the music, uncomment the last line of code.

Fs = 44100; y = audioread("guitartune.wav");% sound(y,Fs)

Buffer the audio signal into overlapping frames, each with 4096 samples. Use an overlap of 512 samples.

winLength = 4096; overlap = 512; [yB,~] = buffer(y,winLength,overlap,"nodelay");

Obtain the zero-crossing rate for each frame. To account for frame overlap, specify the initial state as the previous value of the first sample in each frame.

init = winLength - overlap; state = 0; zcr = [];fori = 1:size(yB,2) zcr = [zcr;zerocrossrate(yB(:,i),InitialState=state)]; state = yB(init,i);end

Plot the audio signal and overlay the zero-crossing rate for each frame.

figure yyaxisleftx = 0:1/Fs:(numel(y)-1)/Fs; plot(x',y) xlabel("Seconds") ylabel("Amplitude") yyaxisrightxx = (1:size(yB,2))*((winLength-overlap)/Fs); plot(xx',zcr) ylabel("Zero-crossing rate")

Figure contains an axes object. The axes object contains 2 objects of type line.

计算的零交点率无缓冲的年代ignal. To obtain a result equivalent to the zero-crossing rate of the buffered signal, setWindowLengthto4096andOverlapLengthto512. Determine if the two results are equal.

zcr_batch = zerocrossrate(y,WindowLength=winLength,OverlapLength=overlap); isequal(zcr_batch,zcr)
ans =logical1

Input Arguments

collapse all

Data, specified as a real-valued vector or matrix. Ifxis a matrix, the function returns the zero-crossing rate as a row vector where each value corresponds to a column of data.

Data Types:single|double

Input timetable, specified as atimetable.TTmust contain uniformly sampled single- or double-precision data. TheRowTimesproperty must contain adurationordatetimevector with increasing and finite values. IfTTis a timetable with a single variable containing a matrix, or a timetable with multiple variables each containing a vector, then the function analyzes each channel independently.

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, whereNameis the argument name andValueis the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and encloseNamein quotes.

Example:zerocrossrate(x,Method="comparison",Level=7,transitionEdge="rising")uses the comparison method to compute the rate at whichxpositively transitions across7.

Previous states ofx, specified as a vector whose number of elements is equal to the number of input channels.

Example:zerocrossrate(x,InitialState=[1 0 –1 3])返回的交叉率a four-channel input signalx.

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

Method for computing the zero-crossing rate, specified as"difference"or"comparison". If you do not specifyMethod, the function uses the difference method to compute the crossing rate.

  • comparison— The function marks theindicesas true where a crossing is fully completed.

  • difference— The function marks theindicesas true whereabs(sign(xi)–sign(xi–1)) > 0.

Example:zerocrossrate(x,Method="comparison")computes the crossing rate ofxusing the comparison method.

Data Types:char|string

Window length over which to compute the crossing rate, specified as a positive integer. The default window length is the signal length.

Example:zerocrossrate(x,WindowLength=20)returns the crossing rates for 20-sample windows inx.

Example:zerocrossrate(x,WindowLength=fs*0.05)returns the crossing rates for 50 ms windows inxgiven a sample ratefs.

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

Number of overlapping samples between adjoining segments, specified as a positive integer. The overlap must be smaller than the window length.

Example:zerocrossrate(x,OverlapLength=0)返回的交叉率segments with no overlap.

Example:zerocrossrate(x,WindowLength=20,OverlapLength=5)返回的交叉率overlapping segments with five samples of overlap.

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

Signal level for which the crossing rate is computed, specified as a real scalar. The function subtracts theLevelvalue from the signal and then finds the zero crossings. If you do not specifyLevel, the function uses the default value of0and returns the zero-crossing rate.

Example:zerocrossrate(x,Level=1)returns the rate at which the input signalxcrosses1.

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

阈值之上和之下Levelvalue over which the crossing rate is computed, specified as a real scalar. The function sets all the values of the input in the range [–threshold,threshold] to0and then finds the zero crossings.

Example:zerocrossrate(x,Threshold=0.1)returns the crossing rate with a tolerance of –0.1 to 0.1.

Note

When you specify bothLevelandThreshold, the function first subtracts the level value from the input and then sets to0the resulting input values that are in the range [–threshold,threshold].

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

转换to include when counting the zero crossings, specified as"falling","rising", or"both". If you specify"falling", the function counts only negative-going transitions. If you specify"rising", the function counts only positive-going transitions.

Example:zerocrossrate(x,TransitionEdge="rising")returns the crossing rate ofxfor only positive-going transitions.

Data Types:char|string

Sign convention, specified as a logical scalar. If you specifyZeroPositiveas true, the function considers0to be positive. If you specifyZeroPositiveas false, the function considers0, –1, and +1to have distinct signs following the convention of thesignfunction.

Example:zerocrossrate(x,ZeroPositive=1)returns the crossing rate of the input signalxand considers zero as positive.

Data Types:logical

Output Arguments

collapse all

Zero-crossing rate, returned as a row vector or a matrix. WhenWindowLengthis equal to the signal length,rateis a row vector whose number of elements is equal to the number of channels inxorTT. WhenWindowLengthis smaller than the signal length, the function returnsrateas a matrix where thei-th row contains the crossing rate for thei-th window and thej-th column corresponds to thej-th input channel.

Number of crossings, returned as anN-by-Mmatrix whereNis the number of windows andMis the number of input channels. Thei-th row corresponds to the crossing count for thei-th window and thej-th column corresponds to the crossing count for thej-th channel.

Logical indices at the signal locations where crossings occur, returned as anN-by-WindowLength-by-Marray whereNis the number of windows andMis the number of input channels.

Note

Indices might not represent exact signal crossing locations. Thezerocrossratefunction returns an index at the next sample following a crossing.

Extended Capabilities

Version History

Introduced in R2021b

See Also

Functions