필터 지우기
필터 지우기

How do i use least square method to fit a nonlinear curve to data set below ?

조회 수: 3 (최근 30일)
How do i use least square method to fit a nonlinear curve to data set below ?
p=[40 50 60 80 100]
r=[230.88 243.5 268.34 278.92 280]

채택된 답변

Scott MacKenzie
Scott MacKenzie 2021년 5월 16일
편집: Scott MacKenzie 2021년 5월 16일
This solution uses polyfit and a log transformation, converting the power-law into a linear equation. There might by an easier way. Perhaps someone else will weigh in with an alternate solution.
p = [40 50 60 80 100];
r = [230.88 243.5 268.34 278.92 280];
% transform r = ap^n into log(r) = log(a) + n log(p)
pLog = log(p);
rLog = log(r);
% do the model fitting and get coefficients
pf = polyfit(pLog, rLog, 1);
b = pf(1);
a = exp(pf(2));
% get squared correlation coefficient
CM = corrcoef(pLog, rLog);
R2 = CM(1,2)^2;
% x/y data for power-law curve from x = 0 to x = 150
x = linspace(0,150);
y = a * x.^b;
% plot curve and scatter data
p1 = plot(x, y);
hold on;
s1 = scatter(p, r, 'filled');
ax = gca;
ax.XLim = [0 150];
ax.YLim = [0 350];
ax.XLabel.String = 'p';
ax.YLabel.String = 'r';
% print equation and line to curve
s = sprintf('%s = %5.3f%s^{%.4f}\n%s^2 = %.4f', '{\itr}', ...
a, '{\itp}', b, '{\itR}', R2);
text(50, 150, s);
line([40, 30], [175, a * 30^b], 'color', 'k');

추가 답변 (1개)

Scott MacKenzie
Scott MacKenzie 2021년 5월 16일
Which non-linear curve? Here are a few options for you, for polynomials with orders 1 through 6:
p = [40 50 60 80 100];
r = [230.88 243.5 268.34 278.92 280];
x = -1000:1000;
tiledlayout('flow');
for i=1:6
pf = polyfit(p, r, i); % assume p is x, r is y
y = polyval(pf, x);
nexttile;
plot(x,y);
end
  댓글 수: 2
maziar
maziar 2021년 5월 16일
thanks but i need to fit a curve like r=ap^n and get a and n .
Scott MacKenzie
Scott MacKenzie 2021년 5월 16일
OK, got it. I've posted another answer for the power-law curve you are interested in.

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

카테고리

Help CenterFile Exchange에서 Interpolation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by