# signal processing – How to make a curve smoothing in matlab?

## signal processing – How to make a curve smoothing in matlab?

Lets define a wavy function:

``````x = 0:.1:20;
y1 = 5*sin(x) + 2*x - x.^2 +.3*x.^3 - .2*(x-15).^4 - 10*x.^2.*cos(x./3+12).^3 + .5*(x-12).^4;
``````

``````r = randi(1000,1,201) - 500;
y2 = y1+r;
``````

Now make a 1D Gaussian filter, normalize it and convolve it with our function:

``````g = gausswin(20); % <-- this value determines the width of the smoothing window
g = g/sum(g);
y3 = conv(y2, g, same)
``````

Lets see the result

``````figure;
hold on;
plot(y1, r, linewidth, 3);
plot(y2, b);
plot(y3, g, linewidth, 3);
``````

Red the original function, blue the noisy version, green the smoothed, recovered function.

another option is to use smooth. I like to use it because it is a single line function. Using the code of the previous answer by @Junuxx:

``````x = 0:.1:20;
y1 = 5*sin(x) + 2*x - x.^2 +.3*x.^3 - .2*(x-15).^4 - 10*x.^2.*cos(x./3+12).^3 + .5*(x-12).^4;
r = randi(1000,1,201) - 500;
y2 = y1+r;
``````

Now apply smooth:

``````ys = smooth(x,y2,0.25,rloess);
plot(x,y2,x,ys)
``````

``````doc smooth
``````

#### signal processing – How to make a curve smoothing in matlab?

`gausswin()` requires the Signal Processing Toolbox

`smooth()` requires the Curve Fitting Toolbox

If you dont have these toolboxes, here is a simple `smooth()` implementation:

smooth.m:

``````function yy = smooth(y, span)
yy = y;
l = length(y);

for i = 1 : l
if i < span
d = i;
else
d = span;
end

w = d - 1;
p2 = floor(w / 2);

if i > (l - p2)
p2 = l - i;
end

p1 = w - p2;

yy(i) = sum(y(i - p1 : i + p2)) / d;
end
end
``````

result for `y3 = smooth(y2, 15)`, using @Junuxx code: