Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the least squares approximation in MATLAB?

For a homework assignment in linear algebra, I have solved the following equation using MATLAB's \ operator (which is the recommended way of doing it):

A = [0.2 0.25; 0.4 0.5; 0.4 0.25];
y = [0.9 1.7 1.2]';
x = A \ y

which produces the following answer:

x =
1.7000
2.0800

For the next part of assignment, I'm supposed to solve the same equation using the least squares approximation (and then compare it against the prior value to see how accurate the approximation is).

How can I find a way of doing that in MATLAB?

Prior work: I have found the function lsqlin, which seems to be able to solve equations of the above type, but I don't understand which arguments to supply it nor in what order.

like image 888
Jakob Avatar asked Dec 02 '09 11:12

Jakob


2 Answers

mldivide, ("\") actually does that too. According to the documentation:

If A is an m-by-n matrix with m ~= n and B is a column vector with m components, or a matrix with several such columns, then X = A\B is the solution in the least squares sense to the under- or overdetermined system of equations AX = B. In other words, X minimizes norm(A*X - B), the length of the vector AX - B. The rank k of A is determined from the QR decomposition with column pivoting (see Algorithm for details). The computed solution X has at most k nonzero elements per column. If k < n, this is usually not the same solution as x = pinv(A)*B, which returns a least squares solution.

So really, what you did in the first assignment was to solve the equation using LSE.

like image 129
Hannes Ovrén Avatar answered Sep 21 '22 02:09

Hannes Ovrén


Does your assignment involve explicitly coding up a least-squares approximation, or just using another function available in MATLAB? If you can use another function, one option is LSQR:

x = lsqr(A,y);
like image 20
gnovice Avatar answered Sep 19 '22 02:09

gnovice