MATLAB: Bug on polyfit output

outputpolyfittilde

Hi, I am wondering why the results change when I call polyfit with the tilde ('~'), in order to obviously surpress the remaining outputs:
>> p = polyfit([1 2 3 5 10], [5 65 84 2 3],1)
p =
-4.7402 51.7087
BUT
>> [p,~,~] = polyfit([1 2 3 5 10], [5 65 84 2 3],1)
p =
-16.8925 31.8000
I thought in both cases p should contain the same coefficients. Does anybody know why there is a difference? The ~ method works fine with other functions for example like size:
>> [p,~] = size([11 11; 11 11;11 11])
p =
3
I use R2016a. Looking forward to your answers. Kind regards!

Best Answer

"Feature" or "Quality of Implementation" depending on your viewpoint...
help polyfit
...
[p,S,mu] = polyfit(x,y,n) also returns mu, which is a two-element vector with centering
and scaling values.
mu(1) is mean(x), and mu(2) is std(x). Using these values, polyfit centers x at zero
and scales it to have unit standard deviation
...
I'd never tried it before with the tilde as the third output argument so wasn't aware it (the tilde, that is) was being counted as if the argument were there, but clearly it is.
>> x=[1 2 3 5 10];
>> [mean(x) std(x)]
ans =
4.2000 3.5637
>> [p,~,mu] = polyfit([1 2 3 5 10], [5 65 84 2 3],1)
p =
-16.8925 31.8000
mu =
4.2000
3.5637
>>
It comes from ancient history of how polyfit was initially implemented; truthfully to have the output variable determine whether the independent variable is/is not scaled is/was a less-than-optimal design and almost certainly wouldn't have made the cut under today's ideas of software design/interface. But, 30 years ago or so when first implemented ideas were far different than are today.
ADDENDUM: However, what's the purpose of using the tilde for trailing return value position holders that you don't want, anyway? Any number of output variables beyond those provided for are automagically dropped; the only purpose/need for the tilde is to not return one (or more) arguments that are positioned prior to one that is desired.
Of course, here's a case because of the unusual input design that the output is dependent upon the number of inputs that if you want the scaling you have to provide the output argument.
I've found it somewhat surprising that TMW hasn't introduced a more capable and modern version into base product rather than restricting only to the toolboxes (which I find somewhat cumbersome albeit more flexible).