Asked by Corey Kovacs
on 14 Sep 2018

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

Answer by Stephen Cobeldick
on 14 Sep 2018

Edited by Stephen Cobeldick
on 14 Sep 2018

Accepted Answer

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

Corey Kovacs
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
on 16 Sep 2018

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.