Specify a linear function in terms of the least squares method approximates the set point table. Then calculate the sum of squares deviations of this linear function in given points.
xi=[1.25 2.34 4.15 5.12 6.05 6.45];
yi=[-1.3 -1.6 -2.3 -3.1 -3.8 -4.1];
I assume that the required polynomial is second-degree, and the answer is:
P = -0.5467x – 0.3894
How to format following equation in Matlab?
sum = $\sum_{i=0}^{n}[p(x_{i})-y_{i}]^2$
Best Answer
symbolic toolbox
is not the usual way to do least square method inMATLAB
, the most used function ispolyfit
andpolyval
, in whichpolyfit
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 inand 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
andyi
, then the most vectorized command to compute this explicitly is, supposedly you have yourp
give as above:noted the dot before the exponential hat, it is for the vectorized arithmetic operation in
MATLAB
. Or simply use the built-in Euclidean norm functionnorm
which returns the $l^2$-norm of a sequence:will give you the same result.