# Find Middle of square wave

5 views (last 30 days)
Russell Senior on 2 Apr 2020
Commented: Star Strider on 2 Apr 2020
I can find the rising edge and falling edge of a square wave, any thoughts on how to find the middle of an arbitrary square wave? I created a simple code using a logical array that finds the rising edges and falling edges, but I can't think of a good way to find the middle of the square. Ideas?
Edit: I'd like to avoid using a for loop. Speed is important since this will be used to process a few GB of data.
clear all
close all
t = 0:100;
x = false(size(t));
x(2:10) = true;
x(25:30) = true;
x(50:75) = true;
x(90:end) = true;
rising = x > [x(1) x(1:end-1)];
falling = x < [x(1) x(1:end-1)];
subplot(3,1,1)
plot(t,x)
subplot(3,1,2)
plot(t,rising,'r')
subplot(3,1,3)
plot(t,falling,'k') Star Strider on 2 Apr 2020
Use the islocalmax function (R2017b and later):
This code plots green upward-pointing triangles at the centre of each pulse:
t = 0:100;
x = false(size(t));
x(2:10) = true;
x(25:30) = true;
x(50:75) = true;
x(90:end) = true;
rising = x > [x(1) x(1:end-1)];
falling = x < [x(1) x(1:end-1)];
ctr = islocalmax(x, 'FlatSelection','center'); % Added
subplot(3,1,1)
plot(t,x)
hold on
hold off
subplot(3,1,2)
plot(t,rising,'r')
subplot(3,1,3)
plot(t,falling,'k')
I did not add them to the last two subplot axes. Copy the hold and plot calls to them if you want to plot them there as well.

Russell Senior on 2 Apr 2020
That is exactly what I was looking for. Thanks for that.
Star Strider on 2 Apr 2020
As always, my pleasure!