我正在尝试使用apply而不是for循环来解决不同初始条件的ode。这是我的代码,显然它不起作用。提前一百万感谢。
################
# Example 6.1.1
################
example611 <- function(t, x, p)
{
with(as.list(c(x,params)), {
list(c(x1 + exp(-x2), -x2))
})
}
params611 <- c(xparam=1, yparam=1);
state611 <- list(x1=-3:3,x2=-3:3);
times611 <- seq(0,1,by=.1);
reptimes = nrow(as.matrix(state611$x1))
ltimes <- rep(list(times=times611), reptimes)
lparams <- rep(list(params=params611), reptimes)
func611 <- rep(list(func=example611), reptimes)
args <-list(y=state611, ltimes, func611, lparams)
res <- apply(args,ode)
答案 0 :(得分:0)
这是一段模拟ODE矩阵并绘制图形的R代码。这使用一些闭包和其他函数式编程范例来回答已发布的问题。
# This is the linear system analysis
library("deSolve")
odefunc <- function(A)
{
function(t,x,p) {
with(as.list(c(x,p)),
{
list(c(A[1,1] * x1 + A[1,2] * x2, A[2,1] * x1 + A[2,2] * x2))
})
}
}
runodesim_func <- function(params, func, times)
{
function(x) {
state <- c(x1=x[1], x2=x[2])
ode(y=state, times=times, func=func, params)
}
}
plotres <- function(res)
{
lines(res[,"x1"], res[,"x2"])
}
analyse <- function(A, times, x)
{
e <- eigen(A)
plot(0, 0, xlim=c(-3,3), ylim=c(-3,3), type='l', xlab='x', ylab='y')
abline(a=0, b=e$vectors[1,2]/e$vectors[2,2], lty=2)
abline(a=0, b=e$vectors[2,1]/e$vectors[1,1], lty=2)
params <- 1
sim = lapply(x,runodesim_func(params,odefunc(A),times))
lapply(sim, plotres)
}