[Math] Matlab: least square method

MATLABstatistics

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 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.

Related Question