在R中解决线性系统

问题描述 投票:0回答:1

我目前正试图在R中求解一个二维线性系统,我有以下函数。

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函数来实现,那将是一个很大的帮助。

先谢谢你了。

r matlab function ode
1个回答
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")
© www.soinside.com 2019 - 2024. All rights reserved.