欧拉在 MATLAB 上的显式方法引发错误的示例

Euler's explicit method on MATLAB raises error with example

这是我在 MATLAB 上的欧拉显式方法的代码

function [t,x] = meuler(f, intervalo, x0, N)
h = (intervalo(2)-intervalo(1))/N;
t = intervalo(1):h:intervalo(2);
x(:,1) = x0(:);
for i = 1:N
    x(i+1,:) = x(i,:) + h*(f(t(i),x(i,:)));
end

它接受另一个文件中定义的函数f。当我尝试 运行 具有以下功能的代码时

function f = funccorazon(t,x)
f1 = x(2);
f2 = 16*x(1)+4*sin(2*t);
f=[f1;f2];

我收到这个错误

>> meuler(@funccorazon, [0 2*pi], [0 2], 1000)
Attempted to access y(2); index out of bounds because numel(y)=1.

Error in funccorazon (line 2)
f1 = y(2);

我也不知道为什么。显然,当我使用 ode45 求解微分方程时,似乎没有任何问题。任何帮助将不胜感激。谢谢!

错误的原因是您需要使用行向量而不是列向量。

首先,在您的函数调用中,将输入 x0 定义为行向量:

meuler(@funccorazon, [0 2*pi], [0,2], 1000)

其次,在funccorazon函数中,类似地定义输出f:

f=[f1,f2];

最后,在 meuler 函数中做以下更改:

x = zeros(N,2);
x(1,:) = x0;