fit a sine wave to a set of data points

3 views (last 30 days)
C.G.
C.G. on 13 May 2022
Answered: Sam Chak on 13 May 2022
I have the dataset attached and the code below to try and fit a wave to the data. Im getting the following error which I can't get past:
yu = max(Qe_mean);
yl = min(Qe_mean);
yr = (yu-yl); % Range of ‘y’
yz = Qe_mean-yu+(yr/2);
zx = time(yz .* circshift(yz,[0 1]) <= 0); % Find zero-crossings
per = 100; % Estimate period
ym = mean(Qe_mean); % Estimate offset
fit = @(b,x) b(1).*(sin(2*pi*x./per + 2*pi/b(2))) + b(3); % Function to fit
fcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function
s = fminsearch(fcn, [yr; -1; ym]) % Minimise Least-Squares % Minimise Least-Squares
xp = linspace(min(x),max(x),per_in);
plot(x,y,'b', xp,fit(s,xp), 'r')
Unable to perform assignment because the size of the left side is 1-by-1 and the size of the
right side is 1-by-100.
Error in fminsearch (line 201)
fv(:,1) = funfcn(x,varargin{:});

Answers (1)

Sam Chak
Sam Chak on 13 May 2022
I've got this. What do you get?
General model Sin8:
f(x) =
a1*sin(b1*x+c1) + a2*sin(b2*x+c2) + a3*sin(b3*x+c3) +
a4*sin(b4*x+c4) + a5*sin(b5*x+c5) + a6*sin(b6*x+c6) +
a7*sin(b7*x+c7) + a8*sin(b8*x+c8)
Coefficients (with 95% confidence bounds):
a1 = 0.603 (-1.979, 3.185)
b1 = 0.03167 (-0.04371, 0.1071)
c1 = -0.08663 (-13.79, 13.61)
a2 = 0.0364 (-0.02684, 0.09964)
b2 = 0.3738 (0.2646, 0.483)
c2 = -0.5175 (-6.054, 5.019)
a3 = 0.05621 (-0.133, 0.2455)
b3 = 0.1469 (0.02797, 0.2658)
c3 = 4.653 (-1.893, 11.2)
a4 = 0.03751 (-0.0287, 0.1037)
b4 = 0.4343 (0.3727, 0.496)
c4 = 2.639 (-0.5437, 5.822)
a5 = 0.04328 (-0.004699, 0.09126)
b5 = 0.3131 (0.267, 0.3593)
c5 = 2.147 (-0.02915, 4.323)
a6 = 0.2174 (-4.843, 5.277)
b6 = 0.05691 (-0.397, 0.5108)
c6 = 0.4076 (-29.88, 30.69)
a7 = 0.02892 (0.01865, 0.03919)
b7 = 0.5653 (0.5512, 0.5793)
c7 = 0.3736 (-0.4235, 1.171)
a8 = 0.02562 (0.01612, 0.03511)
b8 = 1.103 (1.089, 1.116)
c8 = 1.03 (0.2538, 1.805)
Goodness of fit:
SSE: 0.08528
R-square: 0.9849
Adjusted R-square: 0.9804
RMSE: 0.0335

Categories

Find more on Linear and Nonlinear Regression in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!