在R中求解线性系统

时间:2020-05-12 22:24:21

标签: r matlab function ode

我目前正在尝试在R中求解2D线性系统。我具有以下功能:

times <- seq(0,25,.01)
state.linear <- c(X = 2, Y = 0) # Initial State

A <- matrix(c(-.1, 2, -2, -.1), 2, 2)
b <- c(2,0)

  linear2D <- function(t, A, b) {
    with(as.list(c(A, b)), {
      dX <- A*b
      list(c(dX))
    })
  }
out.linear2D <- ode(y = state.linear, times = times, func = linear2D, parms = A)

我想通过deSolve软件包中的ODE求解器来添加它,但是在使用初始功能时遇到了麻烦。我正在尝试翻译MATLAB中的代码:

n = 2;          % 2D system
A = [-.1 2; -2 -.1];  % dynamics
rhs = @(x)A*x;   % right hand side
tspan=[0:.01:25];   % time span
x0 = [2; 0];        % initial conditions
options = odeset('RelTol',1e-10,'AbsTol',1e-10*ones(1,n));
[t,x]=ode45(@(t,x)rhs(x),tspan,x0,options);

但是,目前还不清楚该如何翻译。如果有人可以帮助将MATLAB代码转换为R,以使其通过R中的ODE函数,那将是一个很大的帮助。

谢谢。

1 个答案:

答案 0 :(得分:1)

以下内容回答您的问题吗?请注意以下几点:

  • %*%是矩阵乘积
  • 默认的method = "lsoda"method = "ode45"更好
library("deSolve")

times <- seq(0, 25, .01)
state.linear <- c(X = 2, Y = 0) # Initial State

A <- matrix(c(-.1, 2, -2, -.1), 2, 2)
b <- c(2, 0)

linear2D <- function(t, A, b) {
  with(as.list(c(A, b)), {
    dX <- A %*% b
    list(c(dX))
  })
}

out.linear2D <- ode(y = state.linear, times = times, 
                    func = linear2D, parms = A, method="ode45",
                    atol = 1e-10, rtol = 1e-10)

## time series
plot(out.linear2D)

## phase plot
plot(out.linear2D[, -1], type="l")