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

2 views (last 30 days)
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]

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 16 May 2021
Edited: Scott MacKenzie on 16 May 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');

More Answers (1)

Scott MacKenzie
Scott MacKenzie on 16 May 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

Categories

Find more on Interpolation 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!