<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body text="#000000" bgcolor="#FFFFFF">
<br>
<font face="Courier New">Dear All,<br>
<br>
Trying to convert an old Matlab script to Scilab I miss the
function polyfit, which computes the coefficients of a polynomial
that fits x-y data using the least square method.<br>
<br>
I found the following thread <a moz-do-not-send="true"
href="http://mailinglists.scilab.org/Polynomic-regression-td4030799.html">http://mailinglists.scilab.org/Polynomic-regression-td4030799.html</a>
explaining that one can use the backslash, for instance for a 3rd
degree polynomial, where x and y are column vectors:<br>
<br>
X = [</font><font face="Courier New">ones(x), </font><font
face="Courier New">x, </font><font face="Courier New">x.^2, </font><font
face="Courier New"> </font><font face="Courier New"> </font><font
face="Courier New">x.^3</font><font face="Courier New">]<br>
A = X\y; <br>
<br>
(I changed the order of powers to get the coefficients ready for
horner)<br>
<br>
I implemented a polyfit function using the basic theory of
polynomial regression and I find it is faster </font><font
face="Courier New">by a factor of 1.5-2 </font><font
face="Courier New">than the previously mentioned method.<br>
<br>
The basic algorithm I use is (n = desired degree):<br>
<br>
// Initialize matrix X<br>
X = ones(length(x), n+1);<br>
// Compute Vandermonde's matrix<br>
for k =2:n+1<br>
X(:,k) = X(:,k-1).*x;<br>
end<br>
// Apply the Moore-Penrose pseudoinverse matrix and<br>
// multiply by the dependent data vector to get the<br>
// least squares approximation of the polynomial<br>
// coefficients<br>
A = inv(X'*X)*X'*y;<br>
<br>
I've seen some discussion regarding the need for a polyfit
function in Scilab. The main argument against such a function is
that it is unnecessary since it is a particular case of the
backslash division. This is true, but the above example shows that
users' implementations are not always optimized, and as it is such
a frequent problem, it would be nice to have a native polyfit (or
whatever it may be called) function. <br>
<br>
Regards,<br>
<br>
Federico Miyara<br>
</font>
</body>
</html>