How to fit data to data

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

How can I get MATLAB to find the best values for a and b? What do you mean by "best values?"
I've edited the question to make this more clear

Sign in to comment.

Answers (1)

John D'Errico
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

Products

Asked:

on 2 Mar 2018

Edited:

on 3 Mar 2018

Community Treasure Hunt

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

Start Hunting!