# Zero crossing matlab ## Easy way of finding zero crossing of a function

Hi guys, I have tried all my attempts but not succeeding to get the correct output/plot .

I'm trying to find my zero crossings points that are implicitly the intercestion of x axis, in other words I want to find all the zero crossings points of my signal by interpolation method!.

I've searched in the other threads over this forum and find subjects that are related to what Im asking but not exactly what I want or either their answers weren't totally correct!

I have signal called y1, it's vectors of samples, I sampled it on sample frequency 2048KHz .

accordingly to @ Star Strider code:

t = [1:length(y1)];

y = y1;

zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0);

zx = zci(y);

figure(1)

plot(t, y, '-r')

hold on

plot(t(zx), y(zx), 'bp')

hold off

grid

legend('Signal', 'Approximate Zero-Crossings')

when I do plot , Im not getting zero crossings points that are the intersections of x axis by interpolation method! , here's what I get:  what Im willing to do by method interpolation to find the zero crossings point which gives me like this result: could anyone please help me how can I find the zero crossings points by interpolation to get like the above plot (zero crossings points like they are the intersections with x axis) ?

the code of my interpolation for finding the zero crossings that Im trying is: (Fs=2048Khz) - thanks to

@Walter Roberson @xszm

if size(y1,1) == 1; y1 = y1.'; end

c = size(y1,2);

wl = (0:size(y1,1)-1) / Fs;

Iwl2=360:0.001:740;

loc_frequ1=0;

for i=1:c

y = y1(:,i);

y2=interp1(wl,y,Iwl2);

zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0);

zx = zci(y2);

loczeros1=round(Iwl2(zx));

locfrequ= ismember(Iwl2,loczeros1);

loc_frequ1=loc_frequ1+double(locfrequ);

end

>> c

c =

1

>> zx

zx =

0×1 empty double column vector

>> size(y1)

ans =

9001 1

but the problem with this that this code didn't work and don't know what the problem is, zx isn't giving me the zero crossings point at all ..

Could anyone please help me how can I do and find the zero crossings points by interpolation in matlab? I really searched about other threads that are related to this but the answers weren't enough or didn't work for my case.

## Select a Web Site

### Zero-Crossing Detection

A variable-step solver dynamically adjusts the time step size, causing it to increase when a variable is changing slowly and to decrease when the variable changes rapidly. This behavior causes the solver to take many small steps in the vicinity of a discontinuity because the variable is rapidly changing in this region. This improves accuracy but can lead to excessive simulation times.

Simulink® uses a technique known as zero-crossing detection to accurately locate a discontinuity without resorting to excessively small time steps. Usually this technique improves simulation run time, but it can cause some simulations to halt before the intended completion time.

### Demonstrating Effects of Excessive Zero-Crossing Detection

This example provides three models that illustrate zero-crossing behavior: , , and .

The model demonstrates how excessive zero crossings can cause a simulation to halt before the intended completion time unless you use the adaptive algorithm.

The model uses a better model design, implementing the dynamics of the ball using a double integrator, than .

The model demonstrates how the adaptive algorithm successfully solves a complex system with two distinct zero-crossing requirements.

Consider the model. It uses two single integrators to compute the vertical velocity and position of the ball over the time of the simulation.

1. Open the model by running at the command line.

2. Once the block diagram appears, set the Solver details > Zero-crossing options > Algorithm parameter in the Solver pane of the Model configuration parameters to . Set the stop time of the model to 20 s. You can change this setting in the Simulink toolstrip or the Solver pane of the model configuration parameters.

3. Simulate the model.

You can now view and analyze the simulation results.

Upon closer examination of the last portion of the simulation, you will see that velocity hovers just above zero.

Change the simulation Stop time to 25 s and simulate the model. The simulation stops with an error due to excessive consecutive zero-crossing events at the Compare To Zero and Position blocks.

Simulink will stop the simulation of model 'example_bounce_two_integrators' because the 2 zero crossing signal(s) identified below caused 1000 consecutive zero crossing events in time interval between 20.357636989536076 and 20.357636990631594. -------------------------------------------------------------------------------- Number of consecutive zero-crossings : 1000 Zero-crossing signal name : RelopInput Block type : RelationalOperator Block path : 'example_bounce_two_integrators/Compare To Zero/Compare' -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Number of consecutive zero-crossings : 500 Zero-crossing signal name : IntgLoLimit Block type : Integrator Block path : 'example_bounce_two_integrators/Position' --------------------------------------------------------------------------------

Although you can increase this limit by adjusting the Model Configuration Parameters > Solver > Number of consecutive zero crossings parameter, making that change still does not allow the simulation to go on for 25 s.

Change the Solver details > Zero-crossing options > Algorithm parameter in the Solver pane of the Model configuration parameters to and simulate the model again for 25 s.

Zooming in on the last 5 seconds of the simulation, you can see that the results are more complete and closer to the expected analytical solution of the dynamics of a bouncing ball. The amount of chatter you see is a consequence of the system's states approaching zero and is expected in numerical simulations.

The model uses a Second-Order Integrator block to model the dynamics of the bouncing ball. This is the preferred method to model the double integration of the ball's dynamics for solver performance. To compare the solver performance for and , try running the Solver Profiler on both models. For a detailed comparison of both models, see Simulation of a Bouncing Ball.

For a side-by-side comparison of adaptive and nonadaptive zero-crossing detection algorithms, see Double Bouncing Ball: Use of Adaptive Zero-Crossing Location.

### Preventing Excessive Zero Crossings

Use the following table to prevent excessive zero-crossing errors in your model.

Change TypeChange ProcedureBenefits

Increase the number of allowed zero crossings

Increase the value of the Number of consecutive zero crossings. option on the Solver pane in the Configuration Parameters dialog box.

This may give your model enough time to resolve the zero crossing.

Relax the Signal threshold

Select Adaptive from the Algorithm pull down and increase the value of the Signal threshold option on the Solver pane in the Configuration Parameters dialog box.

The solver requires less time to precisely locate the zero crossing. This can reduce simulation time and eliminate an excessive number of consecutive zero-crossing errors. However, relaxing the Signal threshold may reduce accuracy.

Select Adaptive from the Algorithm drop-down on the Solver pane in the Configuration Parameters dialog box.

This algorithm dynamically adjusts the zero-crossing threshold, which improves accuracy and reduces the number of consecutive zero crossings detected. With this algorithm you have the option of specifying both the Time tolerance and the Signal threshold.

Disable zero-crossing detection for a specific block

1. Clear the Enable zero-crossing detection check box on the block's parameter dialog box.

2. Select from the Zero-crossing control pull down on the Solver pane of the Configuration Parameters dialog box.

Locally disabling zero-crossing detection prevents a specific block from stopping the simulation because of excessive consecutive zero crossings. All other blocks continue to benefit from the increased accuracy that zero-crossing detection provides.

Disable zero-crossing detection for the entire model

Select from the Zero-crossing control pull down on the Solver pane of the Configuration Parameters dialog box.

This prevents zero crossings from being detected anywhere in your model. A consequence is that your model no longer benefits from the increased accuracy that zero-crossing detection provides.

If using the solver, consider adjusting the order of the numerical differentiation formulas

Select a value from the pull down on the Solver pane of the Configuration Parameters dialog box.

Reduce the maximum step size

Enter a value for the option on the Solver pane of the Configuration Parameters dialog box.

The solver takes steps small enough to resolve the zero crossing. However, reducing the step size can increase simulation time, and is seldom necessary when using the adaptive algorithm.

### How the Simulator Can Miss Zero-Crossing Events

The bounce and double-bounce models, in Simulation of a Bouncing Ball and Double Bouncing Ball: Use of Adaptive Zero-Crossing Location show that high-frequency fluctuations about a discontinuity (chattering) can cause a simulation to prematurely halt.

It is also possible for the solver to entirely miss zero crossings if the solver error tolerances are too large. This is possible because the zero-crossing detection technique checks to see if the value of a signal has changed sign after a major time step. A sign change indicates that a zero crossing has occurred, and the zero-crossing algorithm searches for the precise crossing time. However, if a zero crossing occurs within a time step, but the values at the beginning and end of the step do not indicate a sign change, the solver steps over the crossing without detecting it.

The following figure shows a signal that crosses zero. In the first instance, the integrator steps over the event because the sign has not changed between time steps. In the second, the solver detects sign change and therefore detects the zero-crossing event.

Consider the two-integrator implementation of the bounce model.

Profiling of the last 0.5 s of the simulation using the Solver Profiler shows that the simulation detects 44 zero-crossing events at the Compare To Zero block and 22 events at the output of the Position block.

Increase the value of the Relative tolerance parameter to instead of the default . You can change this parameter in the Solver Details section of the Solver pane in the Configuration Parameters dialog or using to specify as .

Profiling the last 0.5 s of the simulation with the new relative tolerance of the solver shows that it detects only 24 zero-crossing events at the Compare To Zero block and 12 events at the output of the Position block.

### Zero-Crossing Detection in Blocks

A block can register a set of zero-crossing variables, each of which is a function of a state variable that can have a discontinuity. The zero-crossing function passes through zero from a positive or negative value when the corresponding discontinuity occurs. The registered zero-crossing variables are updated at the end of each simulation step, and any variable that has changed sign is identified as having had a zero-crossing event.

If any zero crossings are detected, the Simulink software interpolates between the previous and current values of each variable that changed sign to estimate the times of the zero crossings, that is, the discontinuities.

Note

The Zero-Crossing detection algorithm can bracket zero-crossing events only for signals of data type .

#### Blocks That Register Zero Crossings

The following table lists blocks that register zero crossings and explains how the blocks use the zero crossings.

BlockNumber of Zero Crossing Detections

Abs

One, to detect when the input signal crosses zero in either the rising or falling direction.

Backlash

Two, one to detect when the upper threshold is engaged, and one to detect when the lower threshold is engaged.

Compare To Constant

One, to detect when the signal equals a constant.

Compare To Zero

One, to detect when the signal equals zero.

Two, one to detect when the dead zone is entered (the input signal minus the lower limit), and one to detect when the dead zone is exited (the input signal minus the upper limit).

Enable

One, If an Enable port is inside of a Subsystem block, it provides the capability to detect zero crossings. For details, Using Enabled Subsystems.

From File

One, to detect when the input signal has a discontinuity in either the rising or falling direction

From Workspace

One, to detect when the input signal has a discontinuity in either the rising or falling direction

Hit Crossing

One or two. If there is no output port, there is only one zero crossing to detect when the input signal hit the threshold value. If there is an output port, the second zero crossing is used to bring the output back to 0 from 1 to create an impulse-like output.

If

One, to detect when the If condition is met.

Integrator

If the reset port is present, to detect when a reset occurs.

If the output is limited, there are three zero crossings: one to detect when the upper saturation limit is reached, one to detect when the lower saturation limit is reached, and one to detect when saturation is left.

MinMax

One, for each element of the output vector, to detect when an input signal is the new minimum or maximum.

Relational Operator

One, to detect when the specified relation is true.

Relay

One, if the relay is off, to detect the switch-on point. If the relay is on, to detect the switch-off point.

Saturation

Two, one to detect when the upper limit is reached or left, and one to detect when the lower limit is reached or left.

Second-Order Integrator

Five, two to detect when the state x upper or lower limit is reached, two to detect when the state dx/dt upper or lower limit is reached, and one to detect when a state leaves saturation.

Sign

One, to detect when the input crosses through zero.

Signal Editor

One, to detect when the input signal has a discontinuity in either the rising or falling direction

Step

One, to detect the step time.

Switch

One, to detect when the switch condition occurs.

Switch Case

One, to detect when the case condition is met.

Trigger

One, If a Triggered port is inside of a Subsystem block, it provides the capability to detect zero crossings. For details, see Using Triggered Subsystems.

Enabled and Triggered Subsystem

Two, one for the enable port and one for the trigger port. For details, see: Using Enabled and Triggered Subsystems

#### Implementation Example: Saturation Block

An example of a Simulink block that registers zero crossings is the Saturation block. Zero-crossing detection identifies these state events in the Saturation block:

• The input signal reaches the upper limit.

• The input signal leaves the upper limit.

• The input signal reaches the lower limit.

• The input signal leaves the lower limit.

Simulink blocks that define their own state events are considered to have intrinsic zero crossings. Use the Hit Crossing block to receive explicit notification of a zero-crossing event. See Blocks That Register Zero Crossings for a list of blocks that incorporate zero crossings.

The detection of a state event depends on the construction of an internal zero-crossing signal. This signal is not accessible by the block diagram. For the Saturation block, the signal that is used to detect zero crossings for the upper limit is -, where is the input signal.

Zero-crossing signals have a direction attribute, which can have these values:

• rising — A zero crossing occurs when a signal rises to or through zero, or when a signal leaves zero and becomes positive.

• falling — A zero crossing occurs when a signal falls to or through zero, or when a signal leaves zero and becomes negative.

• either — A zero crossing occurs if either a rising or falling condition occurs.

For the Saturation block upper limit, the direction of the zero crossing is either. This enables the entering and leaving saturation events to be detected using the same zero-crossing signal.

## Select a Web Site

### Zero Crossings

S-functions model zero crossings using the mode work vector (or a DWork vector configured as a mode vector) and the continuous zero-crossing vector. Whether the S-function uses mode or DWork vectors, the concept and implementation are the same. For an example using DWork vectors to model zero crossings, see DWork Mode Vector in the “Using Work Vectors” section. The remainder of this section uses mode vectors to model zero crossings.

Elements of the mode vector are integer values. You specify the number of mode vector elements in , using . You can then access the mode vector using . The mode vector values determine how the routine operates when the solvers are homing in on zero crossings. The Simulink® solvers track the zero crossings or state events (i.e., discontinuities in the first derivatives) of some signal, usually a function of an input to your S-function, by looking at the continuous zero crossings. Register the number of continuous zero crossings in , using , then include an routine to calculate the continuous zero crossings. The S-function contains a zero-crossing example. The remainder of this section describes the portions of this S-function that pertain to zero-crossing detection. For a full description of this example, see Zero-Crossing Detection.

First, specifies the sizes for the mode and continuous zero-crossing vectors using the following lines of code.

ssSetNumModes(S, DYNAMICALLY_SIZED); ssSetNumNonsampledZCs(S, DYNAMICALLY_SIZED);

Since the number of modes and continuous zero crossings is dynamically sized, must initialize the actual size of these vectors. In this example, shown below, there is one mode vector for each output element and two continuous zero crossings for each mode. In general, the number of continuous zero crossings needed for each mode depends on the number of events that need to be detected. In this case, each output (mode) needs to detect when it hits the upper or the lower bound, hence two continuous zero crossings per mode.

static void mdlSetWorkWidths(SimStruct *S) { int nModes; int nNonsampledZCs; nModes = numOutput; nNonsampledZCs = 2 * numOutput; ssSetNumModes(S,nModes); ssSetNumNonsampledZCs(S,nNonsampledZCs); }

Next, determines which mode the simulation is running in at the beginning of each major time step. The method stores this information in the mode vector so it is available when calculating outputs at both major and minor time steps.

/* Get the mode vector */ int_T *mode = ssGetModeVector(S); /* Specify three possible mode values.*/ enum { UpperLimitEquation, NonLimitEquation, LowerLimitEquation }; /* Update the mode vector at the beginning of a major time step */ if ( ssIsMajorTimeStep(S) ) { for ( iOutput = 0; iOutput < numOutput; iOutput++ ) { if ( *uPtrs[uIdx] > *upperLimit ) { /* Upper limit is reached. */ mode[iOutput] = UpperLimitEquation; } else if ( *uPtrs[uIdx] < *lowerLimit ) { /* Lower limit is reached. */ mode[iOutput] = LowerLimitEquation; } else { /* Output is not limited. */ mode[iOutput] = NonLimitEquation; } /* Adjust indices to give scalar expansion. */ uIdx += uInc; upperLimit += upperLimitInc; lowerLimit += lowerLimitInc; } /* Reset index to input and limits. */ uIdx = 0; upperLimit = mxGetPr( P_PAR_UPPER_LIMIT ); lowerLimit = mxGetPr( P_PAR_LOWER_LIMIT ); } /* end IsMajorTimeStep */

Output calculations in are done based on the values stored in the mode vector.

for ( iOutput = 0; iOutput < numOutput; iOutput++ ) { if ( mode[iOutput] == UpperLimitEquation ) { /* Output upper limit. */ *y++ = *upperLimit; } else if ( mode[iOutput] == LowerLimitEquation ) { /* Output lower limit. */ *y++ = *lowerLimit; } else { /* Output is equal to input */ *y++ = *uPtrs[uIdx]; }

After outputs are calculated, the Simulink engine calls to determine if a zero crossing has occurred. A zero crossing is detected if any element of the continuous zero-crossing vector switches from negative to positive, or positive to negative. If this occurs, the simulation modifies the step size and recalculates the outputs to try to locate the exact zero crossing. For this example, the values for the continuous zero-crossing vectors are calculated as shown below.

static void mdlZeroCrossings(SimStruct *S) { int_T iOutput; int_T numOutput = ssGetOutputPortWidth(S,0); real_T *zcSignals = ssGetNonsampledZCs(S); InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0); /* Set index and increment for the input signal, upper limit, and lower * limit parameters so that each gives scalar expansion if needed. */ int_T uIdx = 0; int_T uInc = ( ssGetInputPortWidth(S,0) > 1 ); const real_T *upperLimit = mxGetPr( P_PAR_UPPER_LIMIT ); int_T upperLimitInc = ( mxGetNumberOfElements( P_PAR_UPPER_LIMIT ) > 1 ); const real_T *lowerLimit = mxGetPr( P_PAR_LOWER_LIMIT ); int_T lowerLimitInc = ( mxGetNumberOfElements( P_PAR_LOWER_LIMIT ) > 1 ); /*Check if the input has crossed an upper or lower limit */ for ( iOutput = 0; iOutput < numOutput; iOutput++ ) { zcSignals[2*iOutput] = *uPtrs[uIdx] - *upperLimit; zcSignals[2*iOutput+1] = *uPtrs[uIdx] - *lowerLimit; /* Adjust indices to give scalar expansion if needed */ uIdx += uInc; upperLimit += upperLimitInc; lowerLimit += lowerLimitInc; } }

## Easy way of finding zero crossing of a function

You are now following this question If your function is a vector of values, you can use this little function to approximate them:
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Zero-Crossing Indices Of Argument Vector
It is also helpful if you want to usefzero orinterp1 in a loop to get the exact values.
Note that it returns theindices of the zero-crossings, so you have to do the appropriate vector addressing to get the correspondingx andy coordinates of them.
EDIT — (7 Jul 2020 at 2:54)
Another way of defining ‘zci’ is:
zci = @(v) find(diff(sign(v)));
producing the same result. I think that you can interpolate your data. You can find my results as follow. Thanks for Star Strider, I found it for a long time.   There are many ways to try and skin this problem, many people have tried and find varying different levels of success. Here's a function you can use that requires a sinusoidal waveform to approximate 0 intersections.
[out_array] = signal_manip(s_in)
sign_array = []; %predeclaration
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Following for loop checks every spot to create the following numbers:
%For positive numbers, a "1" is placed in an array.
%For negative numbers, a "-1" is placed in an array.
%For a zero, a "0" is placed in an array.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end%end "if s_in > 0"
sign_array = [sign_array,curr_sign]; %gives an output array that shows you all negative and positive numbers
end %end for i = 1:length(s_in)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%following for loop looks for the change points and handles the spots where a 0 occurs.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
curr = sign_array(1,1); %Starting comparison Point
out_array = [] %Predeclaration of array
if ( sign_array(1,i) ~= curr) %if number change detected, mark it.
out_array = [out_array,i];
elseif (sign_array(1,i) == 0) %if we have a zero on the graph, mark it and skip i forward by 1 so as to not have a false hit.
out_array = [out_array,i];

## dsp.ZeroCrossingDetector

### Description

The System object™ counts the number of times the signal crosses zero, or changes sign. To detect if a signal in a given channel crosses zero, the object looks for the following conditions, where, xi-l is the current signal value and xi-1 is the previous signal value:

• xi < 0 and xi-1 > 0

• xi > 0 and xi-1 < 0

• For some positive integer L, xi < 0, xi-l = 0, and xi-L-1 > 0, where .

• For some positive integer L, xi > 0, xi-l = 0, and xi-L-1 < 0, where .

For the first input value, xi-1 and xi-2 are zero.

To count the number of times a signal crosses zero or changes sign:

1. Create the dsp.ZeroCrossingDetector object.

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

### Description

example

returns a zero crossing detection object that calculates the number of times the signal crosses zero.

### Description

example

calculates the number of zero crossings of the input. Each column of the input is treated as an independent channel.

expand all

### — Data inputvector | matrix

Data input whose zero crossings are counted by the object, specified as a vector or a matrix.

Example:

Example:

Data Types: | | | | | | | | | |

expand all

### — Number of zero crossingsscalar | row vector

Number of zero crossings in the data input, returned as one of the following:

• scalar –– When the data input is a column vector, the scalar output is the number of zero crossings in the data input..

• row vector –– When the data input is a matrix, each element in the row vector output is the number of zero crossings in the corresponding column of the data input.

Example:

Example: []

Data Types:

### 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 , use this syntax:

expand all

### Common to All System Objects

 Run System object algorithm Release resources and allow changes to System object property values and input characteristics Reset internal states of System object

collapse all

### Determine Number of Zero Crossings

Note: If you are using R2016a or an earlier release, replace each call to the object with the equivalent syntax. For example, becomes .

Find the number of zero crossings in electrocardiogram data.

EcgData = ecg(500)'; zcd = dsp.ZeroCrossingDetector; numZeroCross = zcd(EcgData)
plot(1:500,EcgData,'b',[0 500],[0 0],'r','linewidth',2)

Introduced in R2012a

You have a modified version of this example. Do you want to open this example with your edits?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

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: .

Select web site

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.

Sours: https://www.mathworks.com/help/dsp/ref/dsp.zerocrossingdetector-system-object.html
Hit Crossing in MATLAB Simulink as Zero Crossing Detector #22

You are now following this Submission

This Matlab code for finding the crossing zero from sin wave

### Cite As

Cingi Kaewkannate (2021). ZeroCrossing.m (https://www.mathworks.com/matlabcentral/fileexchange/47610-zerocrossing-m), MATLAB Central File Exchange. Retrieved .

##### MATLAB Release Compatibility

Created with R2014a

Compatible with any release

##### Platform Compatibility
WindowsmacOSLinux

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

### Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.

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: .

Select web site

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.

Sours: https://www.mathworks.com/matlabcentral/fileexchange/47610-zerocrossing-m

### You will also like:

It was a boy of about Friday ti. All fears immediately disappeared, but on the contrary, the excitement increased. I deliberately tried to make Oksana get out of the water more often, showing the observer all her girlish charms. I don't know why, but I was wildly excited by the realization that someone was looking at Oksana.

2008 2009 2010 2011 2012