zerocrossrate
Zero-crossing rate
Syntax
Description
specifies additional name-value arguments. Use this syntax with any of the input arguments in previous syntaxes.rate
= zerocrossrate(___,Name,Value
)
zerocrossrate(___)
with no output arguments plotsrate
along 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
Count Zero Crossings in Signal
Consider a vector of ones with alternating signs. Plot the data.
x = [1 -1 1 -1 1 -1 1 -1 1 -1]; plot(x)
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. Plotx
and 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 ofx
to be zero by default.
[~,~,indices] = zerocrossrate(x); plot(x) holdonplot(x(indices),'*') holdoff
Compute the zero-crossing rate ofx
using 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 ofx
again 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 ofx
as1
. The rate is equal to the previous result.
rI = zerocrossrate(x,InitialState=1)
rI = 0.9000
Count Level Crossings in Temperature Data
Load a set of temperature readings in Celsius taken every hour at Logan Airport in Boston for the entire month of January, 2011. Create atimetable
and 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
Identify Voiced and Unvoiced Speech Using Zero Crossings
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");
Plotrate
to 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)
Use a threshold of0.1
to differentiate between voiced and unvoiced segments. Create asignalMask
object 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 setls
fromSpeechTranscription.mat
into 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
Zero-Crossing Rate of Streaming Data
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")
计算的零交点率无缓冲的年代ignal. To obtain a result equivalent to the zero-crossing rate of the buffered signal, setWindowLength
to4096
andOverlapLength
to512
. Determine if the two results are equal.
zcr_batch = zerocrossrate(y,WindowLength=winLength,OverlapLength=overlap); isequal(zcr_batch,zcr)
ans =logical1
Input Arguments
x
—Data
real-valued vector|real-valued matrix
Data, specified as a real-valued vector or matrix. Ifx
is 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
TT
—Input timetable
timetable
Input timetable, specified as atimetable
.TT
must contain uniformly sampled single- or double-precision data. TheRowTimesproperty must contain aduration
ordatetime
vector with increasing and finite values. IfTT
is 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
, whereName
is the argument name andValue
is 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 encloseName
in quotes.
Example:zerocrossrate(x,Method="comparison",Level=7,transitionEdge="rising")
uses the comparison method to compute the rate at whichx
positively transitions across7
.
InitialState
—Previous states
0
(default) |vector
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
—Method for computing zero-crossing rate
"difference"
(default) |"comparison"
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 theindices
as true where a crossing is fully completed.difference
— The function marks theindices
as true whereabs(sign(xi)–sign(xi–1)) > 0.
Example:zerocrossrate(x,Method="comparison")
computes the crossing rate ofx
using the comparison method.
Data Types:char
|string
WindowLength
—Window length
positive integer
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 inx
given a sample ratefs
.
Data Types:single
|double
|int8
|int16
|int32
|int64
|uint8
|uint16
|uint32
|uint64
OverlapLength
—Number of overlapping samples
0
(default) |positive integer
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
Level
—Signal level
0
(default) |real scalar
Signal level for which the crossing rate is computed, specified as a real scalar. The function subtracts theLevel
value from the signal and then finds the zero crossings. If you do not specifyLevel
, the function uses the default value of0
and returns the zero-crossing rate.
Example:zerocrossrate(x,Level=1)
returns the rate at which the input signalx
crosses1
.
Data Types:single
|double
|int8
|int16
|int32
|int64
|uint8
|uint16
|uint32
|uint64
Threshold
—Threshold
0
(default) |real scalar
阈值之上和之下Level
value 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
] to0
and 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 bothLevel
andThreshold
, the function first subtracts the level value from the input and then sets to0
the resulting input values that are in the range [–threshold
,threshold
].
Data Types:single
|double
|int8
|int16
|int32
|int64
|uint8
|uint16
|uint32
|uint64
TransitionEdge
—转换
"both"
(default) |"falling"
|"rising"
转换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 ofx
for only positive-going transitions.
Data Types:char
|string
ZeroPositive
—Sign convention
0
orfalse
(default) |1
ortrue
Sign convention, specified as a logical scalar. If you specifyZeroPositive
as true, the function considers0
to be positive. If you specifyZeroPositive
as false, the function considers0
, –1
, and +1
to have distinct signs following the convention of thesign
function.
Example:zerocrossrate(x,ZeroPositive=1)
returns the crossing rate of the input signalx
and considers zero as positive.
Data Types:logical
Output Arguments
rate
— Zero-crossing rate
row vector | matrix
Zero-crossing rate, returned as a row vector or a matrix. WhenWindowLength
is equal to the signal length,rate
is a row vector whose number of elements is equal to the number of channels inx
orTT
. WhenWindowLength
is smaller than the signal length, the function returnsrate
as a matrix where thei-th row contains the crossing rate for thei-th window and thej-th column corresponds to thej-th input channel.
count
— Number of crossings
N-by-Mmatrix
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.
indices
— Logical indices
N-by-WindowLength
-by-Marray
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. Thezerocrossrate
function returns an index at the next sample following a crossing.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Code generation does not support disabling dynamic memory allocation when the window length is specified and the input is more than one channel.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
This function fully supports GPU arrays. For more information, seeRun MATLAB Functions on a GPU(Parallel Computing Toolbox).
Version History
Introduced in R2021b
Abrir ejemplo
Tiene una versión modificada de este ejemplo. ¿Desea abrir este ejemplo con sus modificaciones?
Comando de MATLAB
Ha hecho clic en un enlace que corresponde a este comando de MATLAB:
Ejecute el comando introduciéndolo en la ventana de comandos de MATLAB. Los navegadores web no admiten comandos de MATLAB.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)