# how to implement a moving window with a condition ?

112 views (last 30 days)
NIKHIL VALSAN KULANGARETH on 29 Mar 2018
Edited: Guillaume on 29 Mar 2018
I have an row vector 1x10000. this is a representation of series of spikes with its magnitudes being normalized(maximum amplitude 1) . My aim is to find out number of spikes within every 100 samples. I have defined a spike if the magnitude of spike crosses 0.7 or else neglected. First I should take 1st 100 samples and check for number of spikes. Then I should take samples from 2 to 101 and do the same. Then choose samples from 3 to 102 and repeat this till the sample reaches 10000. How can I implement this.

Guillaume on 29 Mar 2018
Edited: Guillaume on 29 Mar 2018
You can either use conv (i.e. a convolution) to compute a count of something over a sliding window, or since R2016a, movsum:
% FAKE DATA
x = rand(1000,1)
% PARAMETERS
window = 100
threshold = 0.7
%no-loop code:
abovethreshold = x >= threshold;
%with conv:
windowcount = conv(abovethreshold, ones(window, 1), 'valid');
%with movsum:
windowcount = movsum(abovethreshold, window, 'Endpoints', 'discard');

Pawel Jastrzebski on 29 Mar 2018
Edited: Pawel Jastrzebski on 29 Mar 2018
Consider the following code:
% FAKE DATA
x = rand(100,1)
% PARAMETERS
window = 50
threshold = 0.7
LoopCntr = length(x)-window+1
% PREALLOCATION
m = zeros(LoopCntr, window); % moving range
PksCntr = zeros(LoopCntr,1); % peak conter
RowNames = cell(1, LoopCntr); % row names for the table
ColNames = cell(1,window) ; % column names for the table
for i = 1:LoopCntr
% get your values for the moving range into a matrix
m(i,:) = x(i:i+window-1);
% check them for the conditions and count the peaks
PksCntr(i) = nnz(m(i,:)>threshold)
% get the names for rows and columns
RowNames(i) = {[num2str(i) '-' num2str(i+window-1)]};
ColNames(i) = {['V' num2str(i)]}
end
ColNames(end) = {'NoOfPeaks'};
% Convert matrixec to the table
tVal = array2table([m PksCntr]);
% add names to columns and rows
tVal.Properties.VariableNames = ColNames;
tVal.Properties.RowNames = RowNames;
Remarks:
• I'm not sure but chances are you can achieve the same thing without a loop
• Variables window and theshold might me the reserved words if you have any toolboxes installed (not sure)
• Storing everything in the table at the of the code is not necessary but it helps keep the data organised

#### 1 Comment

Guillaume on 29 Mar 2018
"I'm not sure but chances are you can achieve the same thing without a loop"
Of course, it can be done without a loop.