How to use least squares method in Matlab?

nasim picture nasim · May 19, 2015 · Viewed 9.5k times · Source

I have 37 linear equations and 36 variables in the form of a matrix equation; A*X=B . The equations don't have an exact answer. I want to use Matlab least square method to find the answers with the least error. I am new to Matlab so any comments will help. Thank you

Answer

A. Donda picture A. Donda · May 19, 2015

If A is of full rank, i.e. the columns of A are linearly independent, the least-squares solution of an overdetermined system of linear equations

A * x = b

can be found by inverting the normal equations (see Linear Least Squares):

x = inv(A' * A) * A' * b

If A is not of full rank, A' * A is not invertible. Instead, one can use the pseudoinverse of A

x = pinv(A) * b

or Matlab's left-division operator

x = A \ b

Both give the same solution, but the left division is more computationally efficient.

The two latter computation methods can also deal with underdetermined systems of linear equations, but they give different solutions in that case: The pseudoinverse gives the solution where x has the smallest sum of squares, while the left-division operator gives a solution with as many 0 coefficients as possible.