How to create a sliding window function?

43 views (last 30 days)
I have a code called SampEn and would like to modify it to allow multiple calculations over a sliding window in the following fashion: 1. SampEn(data1:200) 2. SampEn(data(2:201) 3. SampEn(data(3:202) 4. and so on, moving one element forward each time until I reach the end of that data set (e.g. if 1000 elements, then the last analyzed set is data(801:1000).
The original code for SampEn is:
function saen = SampEn(data)
r = 0.2*std(data);
N = length(data);
correl = zeros(1,2);
dataMat = zeros(2+1,N-2);
for i = 1:2+1
dataMat(i,:) = data(i:N-2+i-1);
end
for m = 2:2+1
count = zeros(1,N-2);
tempMat = dataMat(1:m,:);
for i = 1:N-m
dist = max(abs(bsxfun(@minus,tempMat(:,i+1:N-2),tempMat(:,i))));
D = (dist < r);
count(i) = sum(D)/(N-2);
end
correl(m-2+1) = sum(count)/(N-2);
end
saen = log(correl(1)/correl(2));
end
There has to be a faster way to do this than manually having to type in each interval..and I can't wrap my brain around it..Thanks

Accepted Answer

Star Strider
Star Strider on 17 Oct 2015
Assuming the length of ‘saen’ does not change between iterations, this is one (partially-tested because I did not run it with ‘SampEn’) way:
L = 1000;
w = 200;
for k1 = 1:L-w+1
datawin(k1,:) = k1:k1+w-1;
saen(k1,:) = SampEn(data(datawin(k1,:)));
end
This saves the index ranges in the event you need them. If you don’t, eliminate the subscript references in ‘datawin’.
  11 Comments
Star Strider
Star Strider on 9 May 2017
My pleasure!
I would appreciate a Vote for my Answer.
Pragati Patel
Pragati Patel on 29 Mar 2022
@Star Strider Hi! My query is i want to calculate the feature i.e SampEn with a 200 bin sliding window and a 100 bin overlap; 1. SampEn(1:200) 2. SampEn(100:300) 3.SampEn(200:400) and so on. How shall i edit the code? Please respond.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!