Smoothing with a nonuniform window size

1 view (last 30 days)
David Honegger on 11 Sep 2021
Answered: Prachi Kulkarni on 21 Sep 2021
Is there an optimized method to smooth data where the window size can vary? Essentially, I'm looking to find (or create)
>> movmean(A,k)
where size(A)==size(k).
A simple but slow working example might look like:
function ys = movmean2(yn,x,k)
ys = NaN(size(yn));
for i = 1:length(yn)
id = abs(x-x(i))<=k(i);
ys(i) = mean(yn(id));
end
end
In my application, which takes it to higher dimensions and large arrays, this is too slow. Can I avoid the loop? Where might I optimize it?

Prachi Kulkarni on 21 Sep 2021
Hi,
Let A be a 1-D array. Let k be a 1-D array of the same length as A, containing the moving mean window length for each corresponding element of A. The following code gives you the moving mean with nonuniform window lengths without using a loop for computation. The loop only creates the function handle.
functionHandleString = "movmeanNonUniform = @(A,k) diag([movmean(A,k(1))";
for i = 2:length(k)
functionHandleString = functionHandleString + "; movmean(A,k(" + num2str(i) + "))";
end
functionHandleString = functionHandleString + "]);";
eval(functionHandleString);
movmeanNonUniform (A,k)