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

1 vue (au cours des 30 derniers jours)
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]

Réponse acceptée

Scott MacKenzie
Scott MacKenzie le 16 Mai 2021
Modifié(e) : Scott MacKenzie le 16 Mai 2021
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');

Plus de réponses (1)

Scott MacKenzie
Scott MacKenzie le 16 Mai 2021
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 commentaires
maziar
maziar le 16 Mai 2021
thanks but i need to fit a curve like r=ap^n and get a and n .
Scott MacKenzie
Scott MacKenzie le 16 Mai 2021
OK, got it. I've posted another answer for the power-law curve you are interested in.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Interpolation dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by