## to find cosine fit and residual ?

### S (view profile)

on 2 Apr 2013

I have this data as X data column

`   1. [624.0397 743.4188 641.3096 764.2928 698.1912 832.8933 799.6397 767.3729 735.1792 703.093 671.0012 638.9143 605.9839 668.0182 0 0 0 0 0 0]`

Y column

`   1. [8.071650105 8.144216751 8.177926597 8.171846343 8.073710465 7.999249364 8.00676841 8.064808175 8.061246346 8.064100517 8.041524691 8.045426565 8.068412239 8.225694432 0 0 0 0 0 0]`

As the same way I am having data set for third column having x data set and again fourth column I am having y data set as so on upto 520, and also all having same number of element mean column having same number of element and some zero values also.

and want to smooth, cosine fit and want to compute residual for this I have tried

```x=[];
y=[];
for j=1:519
x=AC(:,j+1);
y=AC(:,j);
xx=find(y);
xxx=max(xx);
y1=smooth(x,y(1:xxx),'moving',5);
fitted_curve=cos(x);
end
```

errors are ??? Error using ==> smooth at 131 X and Y must be the same length.

So how can I fit in cosine and compute residual of fit.

## Products

No products are associated with this question.

### Tom Lane (view profile)

on 2 Apr 2013

It appears you start with x and y taken from columns of AC, so they are the same length. Then when you call smooth you pass only part of y. Perhaps you also want to pass the same elements of x.

The fit function (Curve Fitting Toolbox) has the ability to fit Fourier series and sums of sines (equivalent to cosines for your purposes). Try "help fit" and see if that gets you pointed in the right direction.

S

### S (view profile)

on 2 Apr 2013

Yes I tried curve fitting toolbox and giving results for a particular one set of x and y, but as I tried code for polyfit and giving results and in the same way I also want to find for cosine fit, how can I proceed?

```x=[];
y=[];
for j=1:4:440
x=AC1(:,j+2);
y=AC1(:,j);
xx=find(y);
xxx=max(xx);
y1=smooth(x(1:xxx),y(1:xxx),'moving',5);
p=polyfit(x(1:xxx),y1,5);
f=polyval(p,x(1:xxx));
for i=1:xxx
AC1(i,j)=f(i);
end
end
```
Tom Lane

### Tom Lane (view profile)

on 2 Apr 2013

If you need to evaluate the fit at specified x values, as you show in your example with polyval, then the output from the fit command supports that directly:

```x = rand(100,1);
y = cos(x) + randn(100,1)/10;
f = fit(x,y,'sin1')
xx = linspace(0,1);
plot(x,y,'bx',xx,f(xx),'r-')
```

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test