In [1]:
## Create the matrix
A = [
4 9 6 0 4 5 3.0
4 9 4 1 9 9 7
4 9 4 6 0 1 0
4 9 6 1 7 6 1
4 9 4 8 7 9 8
4 9 6 2 3 9 9
4 9 4 6 0 1 3
4 9 6 9 4 3 2
4 9 4 9 0 2 5
4 9 4 6 0 0 5
4 9 4 6 0 0 9
]
Out[1]:
11×7 Array{Float64,2}:
 4.0  9.0  6.0  0.0  4.0  5.0  3.0
 4.0  9.0  4.0  1.0  9.0  9.0  7.0
 4.0  9.0  4.0  6.0  0.0  1.0  0.0
 4.0  9.0  6.0  1.0  7.0  6.0  1.0
 4.0  9.0  4.0  8.0  7.0  9.0  8.0
 4.0  9.0  6.0  2.0  3.0  9.0  9.0
 4.0  9.0  4.0  6.0  0.0  1.0  3.0
 4.0  9.0  6.0  9.0  4.0  3.0  2.0
 4.0  9.0  4.0  9.0  0.0  2.0  5.0
 4.0  9.0  4.0  6.0  0.0  0.0  5.0
 4.0  9.0  4.0  6.0  0.0  0.0  9.0
In [2]:
## Create a simple instance of our least squares problem
using Random
n = 25
Random.seed!(1) # make it repeatable
x = 10.0.*rand(n).-5.0
y = 3.0*x .- 2.0 + 2.0*randn(n)
Out[2]:
25-element Array{Float64,1}:
  -8.81729487513707  
  -6.731238759100307 
  -4.944905385416131 
 -16.909018764958656 
  -3.832543730896477 
 -13.111064192313227 
  11.451135520016631 
  12.66686705135274  
 -13.680875005895466 
  12.466455033950812 
   2.117456316673294 
  -2.751369842234359 
  -2.731466628499282 
   6.953889213428011 
  -9.8554871447013   
 -12.045121292839939 
 -13.064676354655038 
 -18.96684914631947  
  -9.039494790765554 
   8.926299285352144 
 -14.007885858804084 
   5.682218711806928 
  11.806155836740949 
  -8.22979923633141  
   3.5216590725098964
In [3]:
## Make a plot
using Plots
pyplot(dpi=300, size=(600,600))
scatter(x, y, label="data")
gui()
In [4]:
##
In [5]:
## Save the picture
pyplot(size=(250,250)) # this is a 2.5-by-2.5 inch picture, suitable for a small graphic
scatter(x, y, label="data")
savefig("least-squares-example-1.pdf")
In [6]:
## Create the matrix A
A = [ones(n) x]
c = A \ y # solve the least squares problem
Out[6]:
2-element Array{Float64,1}:
 -2.067103835285448 
  3.1899583479786853
In [7]:
## Add the line
plot!(x, x -> c[1] + c[2]*x, label="fit")
gui()
In [8]:
## Try the same with the quadratic
n = 25
Random.seed!(1) # make it repeatable
x = 10.0.*rand(n).-5.0
y = -0.5*x.^2 + 3.0*x .- 2.0 + 2.0*randn(n)
scatter(x, y, label="data")
gui()
In [9]:
##
A = [ones(n) x x.^2]
c = A \ y # solve the least squares problem
Out[9]:
3-element Array{Float64,1}:
 -1.5637991074731672
  3.216873552339138 
 -0.5525699480657095