필터 지우기
필터 지우기

Trying to find best fit for cosine curve

조회 수: 51 (최근 30일)
Matthew
Matthew 2016년 4월 21일
댓글: Ali Alamri 2021년 6월 6일
Hello,
I have 4 data points that I have plotted and are supposed to yield a cosine wave. How do I go about finding the best fit for this cosine wave? I understand 4 points is not a lot but am trying to get the best fit I can.
data = [1 4.2101; 2 -33.0595; 3 -5.6488; 4 76.2462]
Thank you for your help!

채택된 답변

Star Strider
Star Strider 2016년 4월 21일
This works:
data = [1 4.2101; 2 -33.0595; 3 -5.6488; 4 76.2462];
x = data(:,1);
y = data(:,2);
yu = max(y);
yl = min(y);
yr = (yu-yl); % Range of ‘y’
yz = y-yu+(yr/2);
zx = x(yz(:) .* circshift(yz(:),[1 0]) <= 0); % Find zero-crossings
per = 2*mean(diff(zx)); % Estimate period
ym = mean(y); % Estimate offset
fit = @(b,x) b(1).*(sin(2*pi*x./b(2) + 2*pi/b(3))) + b(4); % Function to fit
fcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function
s = fminsearch(fcn, [yr; per; -1; ym]) % Minimise Least-Squares
xp = linspace(min(x),max(x));
figure(1)
plot(x,y,'b', xp,fit(s,xp), 'r')
grid
  댓글 수: 11
Star Strider
Star Strider 2018년 2월 24일
Since the sine and cosine are related by a phase difference of pi/2, the phase term here will allow the function to fit both. This is basic trigonometry.
Ali Alamri
Ali Alamri 2021년 6월 6일
How can I constrain this fit to 2pi?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Linear and Nonlinear Regression에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by