如何在 MATLAB 中编写常微分方程?

How to write an Ordinary Differential Equation in MATLAB?

我尝试在 MATLAB 中编写一个常微分方程。

我写了这段代码:

function [y] = odefun(t,y)
t = [0:0.01:10];
y = [0 0]';
y(1) = y(2);
y(2) = sin(2*t)-2*y(2)-2*y(1);  % I get an error here
end

我在这段代码的最后一行遇到错误。 MATLAB 没有告诉我错误是什么。它只是告诉我那一行有错误。

为什么会出现此错误以及如何解决?

您尝试将包含 1001 个元素的向量分配给 y(2)

>> size(sin(2*t)-2*y(2)-2*y(1))

ans =

           1        1001

错误信息很清楚:

In an assignment A(:) = B, the number of elements in A and B must be the same.

此外,yt 永远不会使用,因为您在函数中重新定义了它们。

你想要的是仔细阅读各种 ode 求解器的文档和那里的示例,然后将你的代码更正为

% Solve ODE y''(t)+2*y'(t)+2*y(t) = sin(2*t), y(0)=y'(0)=0
function ydot = odefun(t,y)
  ydot = zeros_like(y)
  ydot(1) = y(2);
  ydot(2) = sin(2*t)-2*y(2)-2*y(1);
end
% or 
% odefun = @(y,t) [ y(2); sin(2*t)-2*y(2)-2*y(1) ]

% define sample points
tspan = [0:0.01:10];
% define initial value to t=tspan(1)
y0 = [0 0]';
[ t, y ] = ode45(odefunc, tspan, y0)
% t,y now contain the times and values that 
% the solution was actually computed for.