symbolic toolbox
is not the usual way to do least square method in MATLAB
, the most used function is polyfit
and polyval
, in which polyfit
will return the coefficients set $\{a_k\}$ in the following fitting polynomial: $ p_n(x) = a_n x^n + a_{n-1} x^{n-1} + \cdots + a_0 $ simply type in
a = polyfit(x,y,1); % fitting polynomial has degree 1
and you will find that a = [-0.54668 -0.38939]
which coincides with what you give.
If you use second degree a = polyfit(x,y,2);
, a
will be [-0.074948 0.033439 -1.234]
.
For the second question, to evaluate $\displaystyle\sum\limits_{i=0}^{n}[p(x_{i})-y_{i}]^2$, say you have two $(n+1)$-array xi
and yi
, then the most vectorized command to compute this explicitly is, supposedly you have your p
give as above:
p = @(x)-0.5467*x-0.3894 S = sum((p(xi)-yi).^2,2)
noted the dot before the exponential hat, it is for the vectorized arithmetic operation in MATLAB
. Or simply use the built-in Euclidean norm function norm
which returns the $l^2$-norm of a sequence:
S = norm(p(xi)-yi); S = S^2;
will give you the same result.