Minimum least square fitting with multiple variable

4 次查看(过去 30 天)
Hello
I am trying to fit my data with a linear trend using MLS fitting. However, I don't understand how the initial guess affects the final results. I realized that by changing the initial guess from x0 = [1 1], the result of my variable change and I'm confused about deciding which one gives me the best fitting.
My working code and data are found below
data = readtable('data.xlsx');
xdata = table2array(data(:,1));
ydata = table2array(data(:,3));
x = linspace(min(xdata), max(xdata));
fun = @(a)a(1).*xdata + a(2) - ydata;
x0 = [1 1];
x1 = lsqnonlin(fun, x0);
figure
plot(xdata,ydata,'o')
hold on
plot(x, x1(1).*x + x1(2))
hold off

回答(1 个)

Stephan
Stephan 2018-12-25
编辑:Stephan 2018-12-25
Hi,
you could use the resnorm to compare the quality of different approaches:
[x, resnorm] = lsqnonlin(...)
But the question is, why do you use a nonlinear approach for a linear problem? The kind of problem you have is usually solved optimal by mldivide (optimal in sense of least squares):
data = sortrows(readtable('data.xlsx'));
xdata = table2array(data(:,1));
ydata = table2array(data(:,3));
xdata(:,2)=1;
x = xdata\ydata;
scatter(xdata(:,1),ydata,'or')
hold on
plot(xdata(:,1), x(1).*xdata(:,1)+x(2))
hold off
fprintf('Results:\nx(1)=%.15f\nx(2)=%.9f',x(1),x(2))
Best regards
Stephan

类别

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