Search code examples
matlaboctavedata-fittingtrigonometry

Octave: How can I fit a sinusoid to my data using Octave?


My goal is to fit a sinusoid to data goming from a datalogger using Octave. The datalogger logs force which is produced using an excenter, so it theoretically should be a sine wave.

I could not find any hint on how to do this elsewhere.

Currently I'm using the function "splinefit" followd by "ppval" to fit my data but I don't realy get the results I hoped from it... Has anybody an idea how I could fit a sinusoid to my data?

Here's my current code I use to fit the data and a scrennshot of the result:

## splinefit force left
spfFL = splinefit(XAxis,forceL,50);    
fitForceL=ppval(spfFL,XAxis);

##middle force left
meanForceL=mean(fitForceL);
middleedForceL=fitForceL-meanForceL;

result spline fit

on the X-Axis I have the 30'000 measurepoints or logs

on the Y-Axis I have the actual measured force values

the data comes from the datalogger in a .csv-file like this


Solution

  • You could do a least squares optimization, using fminsearch

    % sine to fit (in your case your data)
    x = 0:0.01:50;
    y = 2.6*sin(1.2*x+3.1) + 7.3 + 0.2*rand(size(x)); % create some noisy sine with known parameters
    
    % function with parameters
    fun = @(x,p) p(1)*sin(p(2)*x+p(3)) + p(4);  % sine wave with 4 parameters to estimate
    fcn = @(p) sum((fun(x,p)-y).^2);            % cost function to minimize the sum of the squares
    
    % initial guess for parameters
    p0 = [0 0 0 0];
    
    % parameter optimization
    par = fminsearch(fcn, p0);
    
    % see if estimated parameters match measured data
    yest = fun(x, par)
    plot(x,y,x,yest)
    

    Replace x and y with your data. The par variable contains the parameters of the sine, as defined in fun.