Find Interval in Array With Most Updates

2 views (last 30 days)
Michael Daly
Michael Daly on 30 Jan 2020
Edited: Mohammad Sami on 30 Jan 2020
If I have an array of times (seconds), what is the best way to find the maximum updates over a 10 second interval?
times = [1 2 3 4 6 7 10 12 14 15 17 19 20 21 29 30 32 34 36 37 40 41 42 43 44 45 49 50];
My current way does it with a for loop but figured there must be a better way.
interval_counts = zeros(1,length(times));
for ii = 1:length(times)
interval_start = times(ii);
interval_end = interval_start + 10;
cur_inds = times >= interval_start & times < interval_end;
interval_counts(ii) = sum(cur_inds);
end
max(interval_counts)
Appreciate any help!

Answers (1)

Mohammad Sami
Mohammad Sami on 30 Jan 2020
Edited: Mohammad Sami on 30 Jan 2020
Another option can be
% this will work for integer times
times = [1 2 3 4 6 7 10 12 14 15 17 19 20 21 29 30 32 34 36 37 40 41 42 43 44 45 49 50];
one_sec_int = min(times):max(times);
is_update = ismember(one_sec,times);
checking_interval = 10;
num_updates_interval = movsum(is_update,[0 (checking_interval-1)]);
%M = movsum(A,[kb kf]) computes the sum with a window of length kb+kf+1 that includes the element in the current position, kb elements backward, and kf elements forward.
[max_n_updates,idx] = max(num_updates_interval);
first_time_when_max_update = one_sec_int(idx);

Community Treasure Hunt

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

Start Hunting!