How to fit data to data
Show older comments
I have 2 sets of data and I want to fit one to the other through a function e.g
F = [11,21,31,41];
G = [1,2,3,4];
a = 1 % trial solution
b = 1 % trial solution
fit = times(G,a) + b;
%least squares fitting
chi = F-fit;
chi2 = chi.^2;
sums = sum(chi2);
How can I get MATLAB to find the values for a and b which give the lowest sum of square differences (sums)?
2 Comments
Bob Thompson
on 3 Mar 2018
How can I get MATLAB to find the best values for a and b? What do you mean by "best values?"
Andrei Markin
on 3 Mar 2018
Answers (1)
John D'Errico
on 3 Mar 2018
Edited: John D'Errico
on 3 Mar 2018
ab = polyfit(G,F,1);
ab
ab =
10 1
So a is 10, b is 1.
a = ab(1);
b = ab(2);
The solution uses linear least squares, so it is exactly as you have requested. In this simple case of course, the solution will be essentially exact.
Finally, note that there is no need to use the explicit function times to multiply.
f = a*G + b;
would have sufficed, since a is a scalar variable.
As well, if you have the curve fitting toolbox, I would recommend you not use a variable named fit, as then you will be unable to use the FUNCTION named fit.
Categories
Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!