为什么我在 Octave 中出现 "out of bound 1" 错误?

Why am I getting "out of bound 1" error in Octave?

theta = [pi/2; 0; -pi/2; 0]; 
t = linspace(0, 20, 10000);

g = 9.81;
r = 2;
l = 3;
k = 1;


function thetprim = v(theta, t)
  thetprim = [ theta(2); -g/r * sin(theta(1)) - k * (theta(1) - theta(3)); theta(4); -g/l * sin(theta(3)) - k * (theta(3) - theta(1))];
endfunction

y = ode45('v', theta, t);

hold on;
  title('Title')
  xlabel('X Axis');
  ylabel('Y Axis');
  plot(t, [y(:,1), y(:,3)]);
hold off;

disp(theta(2))

在我 运行 这个脚本之后我得到

error: theta(2): out of bound 1 (dimensions are 1x1)

错误,即使在我评论函数和绘图并尝试显示 theta(2) 后它显示了正确的值。这里发生了什么?

我认为您只是以错误的顺序传递参数。

首先,如果您查看 ode45 的文档:

-- [T, Y] = ode45 (FUN, TRANGE, INIT)

你会看到第二个参数是一个范围,第三个是一个初始值。在我看来,你可能在反过来传递论点?

其次,v 函数似乎也不符合 ode45 似乎期望的 'spec'。来自文档:

FUN is a function handle, inline function, or string containing the name of the function that defines the ODE: 'y' = f(t,y)'. The function must accept two inputs where the first is time T and the second is a column vector of unknowns Y.

而您的 v 函数似乎实际上对应于 'f(y,t)' 规范。