Correct way to detect Zero crossing
Show older comments
Hi i am implementing a power-electronics circuit that requires a zero current detector I implemented a crude function that checks if the current (through a current sensor) is more than a small quantity or not but due to this the simulation speed decreased drastically.
function y = ZCD(I)
if(I<1e-8)
y=1;
else
y=0;
end
Is there a more elegant way to find zerocrossings?
Answers (2)
A thought you might want to consider:
if you multiply the current value, y(i) by the previous value y(i-1), this product is only negative when y(i) has crossed zero.
If y(i) and y(i-1) are both positive, the product is positive, likewise, if they are both negative, the product is positive.
zerocross = y(i)*y(i-1) < 0 ;
Now, if you care whether it's rising or falling, you need to test the sign on y(i)
if zerocross
rising = y(i) > 0 ;
falling = y(i) < 0 ; %(or falling = ~rising)
end
You can make this a function :
function zerocross = detectzerocross(x)
persistent last
if isempty(last) % initialize persistent variable
last=0;
end
zerocross = x*last>0; % = TRUE when x crosses zero
last = x;
end
This function "remembers" the last value of x each time you call it.
The entire function can be replaced with
y = I<1e-8;
which will return a logical (true | false). If you want a double (1 | 0),
y = double(I<1e-8);
Note that this doesn't necessarily identify zero crossings. It merely identifies values less than 1e-8.
Categories
Find more on Job and Task Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!