Calculate the duration that variable remains in a specific value
Show older comments
Hello,
i need to calucale, how long are the intervals a variable with a specific value stays until it change again. In the picture below you can see the plot of the variable i am working with (speed vs time in min).

i would like to have a result like this: The Speed 3000 have followed Interval duration in the Dataset
S_3000 = [6 5 4 7 8 9 4 5] % in Minutes or Datapoints
Where the entries of S_3000 are the number of Intervals found in the Dataset. I have tried already some Ideas, but i don't find any solution. I will also attacht the Data i am working with. Thanks in Advance!
Accepted Answer
More Answers (2)
If you have the Image Processing Toolbox, you can get the duration of all the pulses in one line of code simple by calling regionprops:
% Measure duration of each region
props = regionprops(mask, 'Area')
Here is the full demo
s = load('tab.mat');
t = s.tab;
x = t.t;
y = t.s;
subplot(2, 1, 1);
plot(x, y, 'b-', 'LineWidth', 2);
grid on;
hold on;
title('Original Data')
% Plot a line at the threshold.
threshold = 3000;
yline(threshold, 'LineWidth', 2, 'Color', 'r')
title('Original Data')
xlabel('t')
ylabel('S')
%-----------------------------------------------------------------------------------
% Get a logical vector for where y exceeds the threshold.
mask = y > threshold;
% Measure duration of each region
props = regionprops(mask, 'Area');
% Get the durations of all regions into a vector (extracting from the structure)
S_3000 = [props.Area]
% Show histogram of all the durations
subplot(2, 1, 2);
histogram(S_3000);
grid on;
title('Durations of Pulses')
xlabel('Duration')
ylabel('Count')
jason mcilvenny
on 3 Mar 2023
0 votes
Another solution:
idx = t.s > 3000;
transitions = diff(idx);
starts = find(transitions == 1);
ends = find(transitions == -1);
durations = ends - starts;
durdates=t.t(starts);
s3000=timetable(durdates, durations);
bar(s3000.durdates, s3000.durations);
datetick
Categories
Find more on Coordinate Reference Systems 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!
