Mathematica 9 is now available
THIS IS DOCUMENTATION FOR AN OBSOLETE PRODUCT.
SEE THE DOCUMENTATION CENTER FOR THE LATEST INFORMATION.
Mathematica > Mathematics and Algorithms > Matrices and Linear Algebra > Matrix-Based Minimization >

LeastSquares

LeastSquares[m, b]
finds an x which solves the linear least-squares problem for the matrix equation m.xEqualb.
  • The vector x is uniquely determined by the minimization only if Length[x]EqualMatrixRank[m].
  • The argument b can be a matrix, in which case the least-squares minimization is done independently for each column in b.
  • A Method option can also be given. Settings for arbitrary-precision numerical matrices include "Direct" and "IterativeRefinement", and for sparse arrays "Direct" and "Krylov". The default setting of Automatic switches between these methods depending on the matrix given.
Solve a simple least-squares problem:
Solve a simple least-squares problem:
In[1]:=
Click for copyable input
Out[1]=
Use symbolic input:
m is a 3×4 matrix and b is a length-4 vector:
Use exact arithmetic to find a vector x that minimizes ||m.x-b||_2:
Use machine arithmetic:
Use 20-digit precision arithmetic:
Solve the least-squares problem for a random complex matrix:
Use a sparse matrix:
b can be a matrix:
The first column of the b matrix is used to generate the first column of the result:
m is a 20×20 Hilbert matrix and b is a vector such that the solution of m.x = b is known:
With the default tolerance, numerical roundoff is limited so errors are distributed:
With Tolerance->0, numerical roundoff can introduce excessive error:
Specifying a higher tolerance will limit roundoff errors at the expense of a larger residual:
Here is some data:
Define cubic basis functions centered at t with support on the interval [t - 2, t + 2]:
Set up a sparse design matrix for basis functions centered at 0, 1, ..., 10:
Solve the least-squares problem:
When m.xEqualb can be solved exactly, LeastSquares is equivalent to LinearSolve:
m is a 5×2 matrix and b is a length-5 vector:
Solve the least-squares problem:
This is the minimizer of ||m.x-b||_2:
It is also gives the coefficients for the line with least-squares distance to the points:
LeastSquares gives the parameter estimates for a linear model with normal errors:
LinearModelFit fits the model and gives additional information about the fitting:
The parameter estimates:
Extract additional results:
New in 6
Ask a question about this page  |  Suggest an improvement  |  Leave a message for the team