Skip to content

Instantly share code, notes, and snippets.

@Hio-Been
Last active July 27, 2020 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hio-Been/870695616fccedc4c8f6c111714495ff to your computer and use it in GitHub Desktop.
Save Hio-Been/870695616fccedc4c8f6c111714495ff to your computer and use it in GitHub Desktop.
MATLAB function for calculating custom functions within sliding window
function [x_conv, window] = hb_calc_movingwindow( x, winsize, func, gaussOpt )
% Calculating *func* using moving window
% ex) For moving average
% data = hb_calc_movingwindow( data, 100, @nanmean );
%
% Written by hiobeen.han@kaist.ac.kr, 2020-07-27
if nargin < 3, func = @nanmean; end
if nargin < 4, gaussOpt = false; end
v = round(-winsize*.5): round(winsize*.5);
if gaussOpt % Gaussian weight kernel (Sum is equal to 1)
sd = 2.56;
vv = 1/(sd*sqrt(2*pi)) * exp(-((v-mean(v)).^2) / (2*(sd^2)));
window = vv/max(vv); % Scale weight factor [zero to one]
else
window = ones(size(v));
end
x_conv = [];
for idx = 1:length( x )
w = idx - winsize*.5 : idx + winsize * .5;
dat_part1 = nan( [1, length( find( w<1) )] ); % nan padding
dat_part2 = x( w(find(w>0 & w<length(x)+1)));
dat_part3 = nan( [1, length(find(w>length(x)))]); % nan padding
dat = [ dat_part1, dat_part2, dat_part3 ];
x_conv( idx ) = func( dat .* window );
end
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment