我正在尝试做一个 ODE 求解器,但我在函数中的方程与我在lotka()
函数中设置的初始参数之间的向量存在问题TLfit()
。我不明白为什么当我列出 3 个参数时它说我有一个长度为 1 的向量。谁能提供一些见解?
require(deSolve); # for ODE solver
# define the right-hand side of the ODE
lotka <- function(t,y,parms) {
S=y[1]
I=y[2]
R=y[3]
B=parms[1]; G=parms[2]; # parameters, like before
dN=numeric(3) # vector to hold the derivatives
dN[1]=-B*S*I
dN[2]=B*S*I-(G*I)
dN[3]=G*I
return(list(dN))
}
# data
mydata <- read.csv('PlagueBombay.csv')
tvals <- mydata$Week
xvals <-mydata$WeeklyDeaths
# Least squares objective function
TLfit=function(logp) {
p=exp(logp);
parms=p[1:2]; I0=p[3]; times=1:32;
out=ode(I0,times,lotka,parms);
mse=mean((out[,2]-xvals)^2);
return(mse);
}
p0=c(B=.5,G=.5,I0=.5); # initial guess at parameters
logp0=log(p0);
fit=optim(logp0,TLfit);
我得到错误:
Error in checkFunc(Func2, times, y, rho) :
The number of derivatives returned by func() (3) must equal the length of the initial conditions vector (1)