find how many times a signal becomes above a certain signal

2 views (last 30 days)
Dear all,
I have to count the times when a signal goed under a certain value and gets above a different value.
For example: if y < 80 and goes above 85 count as 1, so the next time it does this the output has to be 2.
Thanks

Accepted Answer

Adam Danz
Adam Danz on 20 Nov 2018
I think what you mean is that you want to count the number of times a continuous signal goes below 80 and then later goes above 85. Here's a method that identifies all samples that fall below 80 ("low") and all samples that rise above 85 ("high"). Then it loops through all samples and keeps track of when a "high" follows a recent "low". There's probably a more clever method that doesn't involve loops but this is fast and it works.
It starts by creating fake data so it can be verified.
% Create fake data
data = randi(30, 1, 20) + 70;
% Which samples dip below 80?
isLow = data < 80;
% Which samples rise above 85?
isHigh = data > 85;
% put two index vectors together
isThreshold = [isLow', isHigh'];
% Loop through each sample; for each 'low' detected,
% look for the nest 'high' and increment the counter. There
% might be a better, non-loop way of doing this.
count = 0;
lowFound = false;
highFound = false;
for i = 1 : length(isLow)
% search next row
if lowFound
highFound = isThreshold(i,2);
else
lowFound = isThreshold(i,1);
end
% if a high was found after finding a low, increment counter; reset flags
if lowFound && highFound
count = count + 1;
lowFound = false;
highFound = false;
end
end

More Answers (1)

Image Analyst
Image Analyst on 20 Nov 2018
Assuming each element above 80 is one count, you can do this
count = sum(y > 80);
Assuming that if it's above 80 for multiple indexes and count that as one region, use bwlabel(), which counts the regions:
y = [1 2 81 83 0 84 86 0]
[L, count] = bwlabel(y > 80)
You'll see the labeled regions and the total region count (2 in this example):
y =
1 2 81 83 0 84 86 0
L =
0 0 1 1 0 2 2 0
count =
2

Community Treasure Hunt

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

Start Hunting!