Hello everyone,
I have a signal and would like to transform it into a blocky signal. I looked into the wavelet toolbox and into the rectpulse function but I couldn't find a proper solution yet.
In the screenshot you can see my original signal and the desired result indicated in red. My signal is attached as well. Is there an easy way to achieve this?
I'm looking forward to your ideas.

 Accepted Answer

John D'Errico
John D'Errico on 29 Nov 2017
Edited: John D'Errico on 29 Nov 2017
I'd just just do something trivially simple here.
First, apply movstd. You want sequences where the curve is essentially constant. So a moving standard deviation on blocks of length 20 is a good start.
movlen = 20;
smov = movstd(g,[0,movlen-1]);
prctile(smov,50)
ans =
0.051006
plot(smov,'.')
refline(0,.05)
So it looks like I can find essentially constant blocks. I'll just take the first block that movstd found with a standard deviation
figure
plot(g,'.b')
hold on
movlen = 20;
smov = movstd(g,[0,movlen - 1]); % forward window, of length movlen
tol = prctile(smov,50);
blocks = zeros(0,3);
bend = 0;
ng = numel(g);
nb = 0;
while true
bstart = bend + find(smov(bend+1:(end - (movlen - 1))) <= tol,1,'first');
if isempty(bstart)
break
end
bend = bstart + movlen - 1;
glevel = mean(g(bstart:bend));
% accept the next point in the series as part of this
% constant block if it is within tol*2 from glevel
while ((bend + 1) <= ng) && (abs(g(bend+1) - glevel) < (2*tol))
bend = bend + 1;
glevel = mean(g(bstart:bend));
end
nb = nb + 1;
blocks(nb,:) = [bstart bend, glevel];
% add to the plot
plot([bstart,bend],[glevel,glevel],'r-','linewidth',5)
end
grid on
These blocks were identified, where the series was essentially constant.
blocks
blocks =
83 142 3.796
189 224 0.74361
226 245 1.0945
266 299 0.74265
301 335 0.28457
355 377 4.1491
394 460 4.1478
479 499 4.0829
566 594 4.1121
595 706 4.0629
743 766 0.59833
767 826 0.6795
835 857 0.71696
886 965 4.1666
966 1080 4.0353
1084 1188 4.022
1196 1226 1.5977
1260 1291 4.0637
1301 1374 1.5273
1375 1405 1.6977
1420 1440 1.7762
1443 1464 0.45545
1479 1505 1.5411
1509 1536 1.055
1537 1629 0.80301
1639 1692 3.9861
1693 1789 3.9074
1821 1840 4.0813
Feel free to pick your own choice for the tolerance and window lengths. As you drew that plot to show your goal, my guess is you would want longer windows, with a somewhat larger tolerance.

1 Comment

Hi John,
although I don't understand your code completely it works for me. As you guessed correctly, I had to play with the tolerances to get my desired result.
I have one final question: the value of the "blocks" is the average value of the original signal in this area, right?
Kind regards John

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!