Polyval returning different values than when manually making an equation with polyfit.

3 views (last 30 days)
If I have this set of data:
year = [1928 1932 1936 1948 1952 1956 1964 1968 1972 1976 1980 1984 1988 1992 1996 2000];
finish = [12.2 11.9 11.5 11.9 11.5 11.5 11.4 11.08 11.07 11.08 11.06 10.97 10.54 10.82 10.94 10.75];
and find the line of best fit using polyfit:
Fit1=polyfit(year,finish,1)
This returns an array of:
[-0.0185 47.6837]
If I use polyval to get the y-values of the line of best fit:
mypoly = polyval(Fit1, year)
I get these values:
11.9852 11.9112 11.8371 11.6149 11.5409 11.4668 11.3187 11.2446 11.1705 11.0965 11.0224 10.9484 10.8743 10.8002 10.7262 10.6521
However, if I make an equation myself using the values from Fit1:
myequ = -0.0185*year + 47.6837
I get:
12.0157 11.9417 11.8677 11.6457 11.5717 11.4977 11.3497 11.2757 11.2017 11.1277 11.0537 10.9797 10.9057 10.8317 10.7577 10.6837
Why are the values different? Aren't polyval and my equation supposed to do the same thing?
The thing that's even more strange is when I make an array the has the same values of Fit1 and compare them using isequal, it returns 0(not equal)
Fit1Copy = [-0.0185 47.6837];
comparefit = isequal(Fit1,Fit1Copy)
Returns
0
What's going on!!!??

Accepted Answer

John D'Errico
John D'Errico on 21 Sep 2015
Edited: John D'Errico on 21 Sep 2015
What is going in is you don't understand that MATLAB does not print out every digit of a number that is stored. If it did, you would quickly ask how to display only a few digits. (And, yes, that is a common question asked by people, those who have the format setting at a longer value.)
Fit1=polyfit(year,finish,1)
Fit1 =
-0.018516 47.684
format long g
Fit1=polyfit(year,finish,1)
Fit1 =
-0.0185157815631264 47.6836673346697
In the second case, I told MATLAB to use a longer display format. There is a difference. So when you used the APPROXIMATE values displayed in the command window, you got different numbers. Why should you be remotely surprised? If you use different numbers you WILL get different prediction.
Note that in fact, even the numbers displayed with "format long g" are STILL only approximate.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!