Search code examples
octave

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))

After I run this script I get

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

error, even though after I comment the function and a plot and try displaying theta(2) it shows the correct value. What is going on in here?


Solution

  • I think you are simply passing arguments in the wrong order.

    Firstly, if you look at the documentation of ode45:

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

    you'll see that the second argument is a range, and the third is an initial value. It seems to me like you may be passing arguments the other way round?

    Secondly, the v function also seems to not be according to 'spec' for what ode45 seems to expect. From the documentation:

    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.

    whereas your v function seems to effectively correspond to a 'f(y,t)' spec instead.