Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab到R的循环转换_R_Matlab_For Loop - Fatal编程技术网

Matlab到R的循环转换

Matlab到R的循环转换,r,matlab,for-loop,R,Matlab,For Loop,我目前正在尝试将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, parameter

我目前正在尝试将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)
}

参数试试这个

库(deSolve)
参数试试这个

库(deSolve)

参数
状态
是一个向量。在R中,向量只有“一”维,即使用
状态[[i]]
提取元素i。然而,即使进行了此更改,循环也会在第三次迭代后中断,因为状态只有三个元素,而您的循环超过1:1000。。。。也许你指的是
out
而不是
state
。对不起,我指的是out而不是state。我将代码更改为out[[I]]和out[,I],但现在收到错误“eval中的错误(替换(expr),data,enclose=parent.frame()):找不到对象“对不起”。使用
out
使用
out[i,]
就可以了,因为
out
是一个矩阵。(:但代码仍将引发错误,因为您尚未将dx初始化为矩阵,..see我的答案
state
是一个向量。在R中,向量只有“一”维,即使用
state[[i]]
提取元素i。但是,即使进行了此更改,循环也会在第三次迭代后中断,因为state只有三个元素,而您的循环比为1:1000……也许您的意思是
out
而不是
state
。对不起,我的意思是out而不是state。我将代码更改为out[[i]]和out[,i]但是我现在收到了错误“error in eval(replacement(expr),data,enclose=parent.frame()):object'Y'not found”抱歉。使用
out[i,]
可以,因为
out
是一个矩阵。(:但是代码仍然会引发错误,因为您还没有将dx初始化为矩阵,请参见我的答案。)