#Nonlinear Least Squares
using Statistics, Printf, Dates, LinearAlgebra, DelimitedFiles, Distributions
Copyright By PowCoder代写 加微信 powcoder
#Defining the data as given in the problem
xdata = [-2,-1.64,-1.33,-0.7,0,0.45,1.2,1.64,2.32,2.9]
ydata = [0.699369,0.700462,0.695354,1.03905,1.97389,2.41143,1.91091,0.919576,-0.730975,-1.42001]
#Intitial guesses for the parameters θ = [p1, p2]
θinitial = [1,0.2]
#For matrix/vector dimensions
n = length(xdata) #number of observations
k = length(θinitial) #number of parameters
#First defining the function we would like to fit
F(X,θ)=θ[1]*cos.(θ[2]*X)+θ[2]*sin.(θ[1]*X)
#Defining all the functions: xtilda, ytilda, θOLS
function xtilda(X,θ,y) #xtilda is the jacobian
jacobian = zeros(n,k)
jacobian[:,1] = cos.(θ[2].*X).+θ[2].*cos.(θ[1].*X).*X #partial derivative of F(X,θ) wrt θ[1] (i.e. p1) for column 1 of jacobian
jacobian[:,2] = -θ[1].*sin.(θ[2].*X).*X.+sin.(θ[1].*X) #partial derivative F(X,θ) wrt θ[2] (i.e. p2) for column 2 of jacobian
return jacobian
function ytilda(X,θ,y)
ytild = zeros(n,1)
ytild = y .- F(X,θ) .+ xtilda(X,θ,y)*θ
return ytild
function θOLS(X,θ,y) #running OLS to generate new θ.
θ1 = (inv((transpose(xtilda(X,θ,y)))*xtilda(X,θ,y)))*(transpose(xtilda(X,θ,y))*ytilda(X,θ,y))
#For first iteration, treating θinitial as if it had just come out of the function, so calling it θnew. This will make the while loop work!
θnew = θinitial
# While loop to iterate.
while true
#Loop takes θnew as θold to then generate new θnew until the difference is sufficiently small (i.e. convergence).
θold = θnew
θnew = θOLS(xdata, θold, ydata) #using our OLS function to generate a new θ with our old θ.
diff = abs.(θnew .- θold)
if maximum(diff) <= 0.0000001 #threshold value, want distance to be sufficiently small.
println(θnew) #This prints our iterations ending with the final θnew (the one we have converged on).
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com