The least squares solution of a linear system: LSQ, lsq

### 5.61.9 The least squares solution of a linear system: LSQ, lsq

The lsq (or LSQ) command takes two arguments; a matrix A and a vector or matrix B.
lsq returns the least squares solution to the equation A*X = B.

Input:

LSQ([[1,2],[3,4]], [5,11])

Output:

[[1],[2]]

Input:

LSQ([[1,2], [3,4]], [[5,7], [11,9]])

Output:

[[1,-5],[2,6]]

Note that
Input:

linsolve([[1,2],[3,4],[3,6]]*[x, y] - [5,11,13],[x, y])

Output:

[]

since the linear system has no solution. We can still find the least squares solution
Input:

LSQ([[1,2],[3,4],[3,6]],[5,11,13])

Output:

[[11/5],[11/10]]

The least squares solution
Input:

LSQ ([[3,4]], [12])

Output:

[[36/25],[48/25]]

represents the point on the line 3x + 4y = 12 closest to the origin;
Input:

coordinates(projection(line(3*x+4*y=12),point(0)))

Output:

[36/25,48/25]