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

4 次查看(过去 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

类别

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