Counting numbers over a threshold in a row

I have 6 columns of values (about 5200 values in each column). Each column corresponds to a different location (variable). I want to count how many times there are 48 consecutive values at or above 50 in each column. I would like a single number to output for each column indicating the number of instances where a value at or above 50 occurs consecutively for 48 rows or more. Many thanks for you help.

 Accepted Answer

demoarray = randi(500, 5200, 6); %demodata
threshold = 50;
minrunlength = 48;
runedges = diff([false(1, size(demoarray, 2)); demoarray >= threshold; false(1, size(demoarray, 2))]); %detect where in the columns the array transition from below to above threshold (1) and back (-1)
[edgerow, edgecol] = find(runedges); %row is where the transition happens. odd indices is guaranteed to be below to above, even indices above to below
runlengths = edgerow(2:2:end) - edgerow(1:2:end); %length of runs, correspond to columns edgecol(1:2:end) (equal to edgecol(2:2:end))
longruns = runlengths >= minrunlength;
numruns = accumarray(edgecol(2:2:end), longruns).' %sum per column

2 Comments

This is perfect. Thank you so much! As a follow up - how can I pull out what the length of the runs above 50 are? (I would like to know how many consecutive values over 50 there are when they are at or above 48).
Just figured out that this code will give the length of runs already in a previous step. Thanks!

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!