5 views (last 30 days)

David Young
on 25 Apr 2016

The answer to problems involving a sliding window is very often to use the convolution operation, as here.

% some random test data, with 1s, 2s and 4s (mainly 2s)

N = 800; % length of series

S = ones(1, N);

r = rand(1, N);

S(r < 0.75) = 2;

S(r > 0.9) = 4;

fprintf('First 20 values: '); fprintf('%d ', S(1:20)); fprintf('\n');

% Now the computation to find where a window of 100 has more than a

% certain fraction of twos

% parameters for the search

windowLength = 100;

testPercent = 80;

% find which of the values are 2

twoPositions = S == 2;

% count the number of twos in each window of length 100

twoSums = conv(double(twoPositions), ones(1, windowLength), 'valid');

% find the positions where the threshold is exceeded

manyTwos = find(twoSums >= windowLength * testPercent / 100);

% Print out the positions of the start of the window where

% there are the required number of twos

fprintf('Positions with many twos: '); fprintf('%d ', manyTwos); fprintf('\n');

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/280933-create-a-sliding-window-to-determine-when-a-of-numbers-in-a-sequence-equal-a-certain-value#comment_361567

⋮## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/280933-create-a-sliding-window-to-determine-when-a-of-numbers-in-a-sequence-equal-a-certain-value#comment_361567

Sign in to comment.