Smoothing data without using inbuilt functions
6 views (last 30 days)
Show older comments
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
Smoothed = CTask2p1_f(x,width);
figure
plot(t,x,'bo',t,Smoothed,'r')
xlabel('Index')
ylabel('Data Value')
title('Smoothing Filter')
legend('Original Data','Smoothed')
Thanks
0 Comments
Accepted Answer
Stephen23
on 14 Sep 2018
Edited: Stephen23
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:
function output = CTask2p1_f(x, width)
% ADD COMMENTS and INPUT and OUTPUT DESCRIPTIONS!
%
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
2 Comments
Kh zaa
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
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!