Polyfit isn't returning linear gradient and intercept
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
testx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
testy =[4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
[PolyCoeff, S, mu] = polyfit(testx, testy, 1)
So my question is - why isn't PolyCoeff returning (1) as 2, and (2) as 2? Where are 6 and 13 coming from? am I missing something really silly and obvious?
0 Kommentare
Akzeptierte Antwort
dpb
am 3 Aug. 2025
testx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
testy =[4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
[PolyCoeff] = polyfit(testx, testy, 1)
What you're missing is that according to the documentation for polyfit, when you ask for the optional third output of the mean,
4 Kommentare
dpb
am 4 Aug. 2025
Bearbeitet: dpb
am 4 Aug. 2025
"...I didn't realise that meant it would also retroactively change the coefficient output. "
testx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
testy = [4, 6, 8, 10, 12, 14, 16, 18, 20, 22];
testz = zscore(testx) % standardize the independent variable
[mean(testz) std(testz)]
and, indeed, as advertised mean, std deviation.
Now,
polyfit(testz,testy,1) % fit vs z instead of vs x
and you see you get the coefficients returned by polyfit in the three-output case. It is the same as if the coefficients were scaled after fitting y vs x but polyfit actually uses the z-score values as the independent variable to improve numerical precision for higher-order polynomials, This is shown in the Alogorithms section of the documentation.
"I will have to read and understand documentation more closely in future! I took that it was such a basic function for granted!"
<LOL> Yes, Mathworks works very diligently to ensure that computations are as accurate as possible so what seems trivial on the surface may have very in-dpeth implementation consequences.
In the case of polyfit being one of the historical functions that has been included since the very early days, its implementation if beginning today would be unlikely to have this behavior at the user level of changing the algorithm based on the expected return variable(s) but would be implemented with named parameter pairs to control the behavior. But, it remains as is for backward compatibility.
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!