Skip to main content
add averaging part.
Source Link
shabbychef
  • 15k
  • 9
  • 58
  • 100

I can do this easily in Matlab and duck while you downvote me:

%given vector x, windowsize, slide 
idx1 = 1:slide:numel(x);
idx2 = min(numel(x) + 1,idx1 + windowsize);  %sic on +1 here and no -1;
cx = [0;cumsum(x(:))];  %pad out a zero, perform a cumulative sum;
rv = (cx(idx2) - cx(idx1);) / windowsize; %tada! the answer!

as a side effect, idx1 is the index of the element in the sum. I am sure this can be easily translated into R. The idiom first:skip:last in Matlab gives the array first, first+skip, first+2skip, ..., first + n skip, where the last element in the array is no greater than last.

edit: I had omitted the averaging part (divide by windowsize).

I can do this easily in Matlab and duck while you downvote me:

%given vector x, windowsize, slide 
idx1 = 1:slide:numel(x);
idx2 = min(numel(x) + 1,idx1 + windowsize);  %sic on +1 here and no -1;
cx = [0;cumsum(x(:))];  %pad out a zero, perform a cumulative sum;
rv = cx(idx2) - cx(idx1); %tada!

as a side effect, idx1 is the index of the element in the sum. I am sure this can be easily translated into R. The idiom first:skip:last in Matlab gives the array first, first+skip, first+2skip, ..., first + n skip, where the last element in the array is no greater than last.

I can do this easily in Matlab and duck while you downvote me:

%given vector x, windowsize, slide 
idx1 = 1:slide:numel(x);
idx2 = min(numel(x) + 1,idx1 + windowsize);  %sic on +1 here and no -1;
cx = [0;cumsum(x(:))];  %pad out a zero, perform a cumulative sum;
rv = (cx(idx2) - cx(idx1)) / windowsize; %tada! the answer!

as a side effect, idx1 is the index of the element in the sum. I am sure this can be easily translated into R. The idiom first:skip:last in Matlab gives the array first, first+skip, first+2skip, ..., first + n skip, where the last element in the array is no greater than last.

edit: I had omitted the averaging part (divide by windowsize).

Source Link
shabbychef
  • 15k
  • 9
  • 58
  • 100

I can do this easily in Matlab and duck while you downvote me:

%given vector x, windowsize, slide 
idx1 = 1:slide:numel(x);
idx2 = min(numel(x) + 1,idx1 + windowsize);  %sic on +1 here and no -1;
cx = [0;cumsum(x(:))];  %pad out a zero, perform a cumulative sum;
rv = cx(idx2) - cx(idx1); %tada!

as a side effect, idx1 is the index of the element in the sum. I am sure this can be easily translated into R. The idiom first:skip:last in Matlab gives the array first, first+skip, first+2skip, ..., first + n skip, where the last element in the array is no greater than last.