## Smoothing data without using inbuilt functions

### Corey Kovacs (view profile)

on 14 Sep 2018
Latest activity Commented on by Kh zaa

on 16 Sep 2018

### Stephen Cobeldick (view profile)

I have a random set of noisy data and need to smooth it without using inbuilt functions. I believe my function and script are close to achieving this. However, they only work for a width of 5, I am unsure how to change the function in order to work for any width size. Function:
function smoothed = CTask2p1_f (x, width)
% Left
for n = 1:2
smoothed(1) = x(1);
smoothed(2) = mean(x(1):x(3));
end
% Middle
for n = 3:98
W = (width - 1) / 2; % Width should be odd
smoothed(n) = mean (x(n-W:n+W));
end
% Right
for n = 99:100
smoothed(99) = mean(x(98):x(100));
smoothed(100) = x(100);
end
end
Script:
t = linspace(0,1,100);
noise = rand(1,length(t));
x = cos(2*pi*t)+0.5*(rand(size(noise))-0.5);
width = input('Please enter filter width: ');
if rem(width,2) == 0
disp('ERROR! Width must be odd. The program will continue with the inputted width plus 1.')
width = width + 1;
end
figure
plot(t,x,'bo',t,Smoothed,'r')
xlabel('Index')
ylabel('Data Value')
title('Smoothing Filter')
legend('Original Data','Smoothed')
Thanks

### Stephen Cobeldick (view profile)

on 14 Sep 2018
Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 14 Sep 2018

Currently your Left and Right loops are superfluous, as each loop iteration does exactly the same thing. But to write a version where the width can change, you could use those loops and change the indices inside the loop.... or you could easily combine them all into one loop, like this:
%
assert(mod(width,2)==1,'width must be odd')
%
output = x; % preallocate for efficiency
offset = fix(width/2);
for k = 1:numel(x)
idx = max(1,k-offset):min(numel(x),k+offset);
output(k) = mean(x(idx));
end
end

Corey Kovacs

### Corey Kovacs (view profile)

on 16 Sep 2018
Thank you, that worked, just a few follow up questions.
1. The function you provided replaces the need to have my left and right loops. Am i correct in saying it replaces my middle loop as well?
2. Assert is used to check if width is odd?
3. Fix rounds the offset value down to the nearest whole number?
Thank you, and sorry if the questions are tedious, just want to make sure I understand the function.
Kh zaa

### Kh zaa (view profile)

on 16 Sep 2018
I use level-1 s-function in my simulink model. Measurements of 5 variables are collected in simulink and sent to s-function. In order to filter out some of measurements noise, i need to use the average of the snapshots received over a a time window (i.e. 2 second). how i can do that ? thanks in advance