我目前正在尝试将MATLAB代码转换为R,并运行一个循环来找到方程的导数。
MATLAB:
for i=1:length(x)
dx(i,:) = lorenz(0,x(i,:),sigma,beta,rho);
end
我在R:中尝试的代码
parameters <- c(s = 10, r = 28, b = 8/3)
state <- c(X = -8, Y = 7, Z = 27)
lorenz <- function(t, state, parameters) {
with(as.list(c(state, parameters)), {
dX <- s * (Y - X)
dY <- X * (r - Z) - Y
dZ <- X * Y - b * Z
list(c(dX, dY, dZ))
})
}
times <- seq(0.001, 1, by = 0.001)
out <- ode(y = state, times = times, func = lorenz, parms = parameters)
dx <- NULL
for (i in 1:1000){
dx[i,] <- lorenz(0,state[i,],parameters)
}
我一直收到错误"状态[I,]错误:尺寸数量不正确",知道为什么吗?
试试这个
library(deSolve)
parameters <- c(s = 10, r = 28, b = 8/3)
state <- c(X = -8, Y = 7, Z = 27)
lorenz <- function(t, state, parameters) {
with(as.list(c(state, parameters)), {
dX <- s * (Y - X)
dY <- X * (r - Z) - Y
dZ <- X * Y - b * Z
list(c(dX, dY, dZ))
})
}
times <- seq(0.001, 1, by = 0.001)
out <- ode(y = state, times = times, func = lorenz, parms = parameters)
# Set up matrix
dx <- matrix(NA, nrow = 1000, ncol = 3)
for (i in 1:1000){
# lorenz returns a list with one element. To assign to dx you have extract the list element using [[1]]
dx[i,] <- lorenz(0,out[i,],parameters)[[1]]
}
head(dx)
#> [,1] [,2] [,3]
#> [1,] 150.00000000 -15.00000000 -128.0000000
#> [2,] 148.35404862 -15.83440159 -126.4953894
#> [3,] 146.71639504 -16.62054372 -125.0045611
#> [4,] 145.08747674 -17.35986863 -123.5280889
#> [5,] 143.46759235 -18.05374748 -122.0664153
#> [6,] 141.85715318 -18.70357479 -120.6200236
由reprex包(v0.3.0(于2020-03-20创建