MATLAB: ODE45: Index exceeds the number of array elements (1).

MATLABode45

Hi, I'm struggling with figuring out the error in my code. I get the error:
Index exceeds the number of array elements (1).
Error in
MatLabProject>@(t,u)[u(2);((-g(2*m1+m2*sin(u(1))))-(g*m2*sin(u(1)-2*u(3)))-(2*m2*sin(u(1)-u(3))*(L2*(u(4)^2+L1*(u(2))^2*cos(u(1)-u(3))))))/(L1*(2*m1+m2-m2*cos(2*u(1)-2*u(3))));u(4);(2*sin(u(1)-u(3))*(L1*(u(2))^2*(m1+m2)+g*(m1+m2)*cos(u(1))+L2*u(4)^2*m2*cos(u(1)-u(3))))/(L2*(2*m1+m2-m2*cos(2*u(1)-2*u(3))))]
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets
args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name,
ode, tspan, y0, options, varargin);
Error in MatLabProject (line 21)
[t,u] = ode45(f,tspan,u0); %ODE to solve system

The code I have is below, and I've tried manipulating the matrix but can't figure out where the error is. Thanks! All help appreciated
%% Initialize
m1=10; %mass 1 (kg)
m2=5; %mass 2 (kg)
L1=2; %distance 1 (m)
L2=1; %distance 2 (m)
Tf=10; %Final Time (s)
g=9.81; %Gravity (m/s^2)
%% Create functions and systems of EQ's
f = @(t,u) [u(2);...
((-g(2*m1+m2*sin(u(1))))-(g*m2*sin(u(1)-2*u(3)))-(2*m2*sin(u(1)-u(3))*(L2*(u(4)^2+L1*(u(2))^2*cos(u(1)-u(3))))))/(L1*(2*m1+m2-m2*cos(2*u(1)-2*u(3))));...
u(4);...
(2*sin(u(1)-u(3))*(L1*(u(2))^2*(m1+m2)+g*(m1+m2)*cos(u(1))+L2*u(4)^2*m2*cos(u(1)-u(3))))/(L2*(2*m1+m2-m2*cos(2*u(1)-2*u(3))))];
%% Set Span, Initial Conditions
u0=[0,0,0,0]; %u1,w1,u2,w2
tspan=[0,Tf]; %Time
%% Solve with ode 45
[t,u] = ode45(f,tspan,u0); %ODE to solve system

Best Answer

In your function you have g(expression) . g is a scalar variable so that is an indexing request. Remember there is no implied multiplication in MATLAB.
Related Question