#Exponential model
fun=function(th,x){
y = th[2]+((th[1]-th[2])*exp(-th[3]*x))
return(y)
}
fun(th,x) #try it out -- should give you fitted values
#Calculate the residual sum of squares
resid=function(th,x,y){
yhat=fun(th,x)
rss=t(y-yhat)%*%(y-yhat)
return(rss)
}
resid(th,x,y) #try it out -- should give a scalar for output
#Calulate the Jacobian matrix
firder=function(th,x){
j1=exp(-th[3]*x)
j2=1-j1
j3=-x*(th[1]-th[2])*exp(-th[3]*x)
j=cbind(j1,j2,j3)
return(j)
}
firder(th,x)
#Calculate the Second Derivatives
secder=function(th,x){
h11=rep(0,times=length(x))
h21=h11
h22=h11
h31=-x*exp(-th[3]*x)
h32=-h31
h33=(x**2)*((th[1]-th[2])*exp(-th[3]*x))
hmat=cbind(h11,h21,h22,h31,h32,h33)
return(hmat)
}
secder(th,x)
#Gradient evaluated at "th"
grad=function(th,x,y){
fd=firder(th,x)
hm=secder(th,x)
yhat=fun(th,x)
r=y-yhat