Attempted to access x(2); index out of bounds because numel(x)=1 for an ODE function

1 view (last 30 days)
I have written a code for a 2 DOF equation transformation which follows like wise,
function:
function [dx] = dx(m1,m2,k1,k2,c1,c2,x,t,time,P_1,P_2)
dx = zeros(4,1);
dx(1) = x(2);
dx(3) = x(4);
dx(2) = (interp1(time,P_1/m1,t,'spline'))+(1/m1)*(-(c1+c2)*x(2)+(c2*x(4))-(k1+k2)*x(1)+(k2)*x(3));
dx(4) = (interp1(time,P_2/m2,t,'spline'))+(1/m1)*((c2)*x(2)-(c2*x(4))+(k2)*x(1)-(k2)*x(3));
end
Main Script:
clear all; clc;
% For 1st Mass system
W1 = 53000;
k1 = 31000;
c1 = 300;
Po_1 = 0;
W_bar = 20;
phi_1 = 0;
% For 2nd Mass system
W2 = 26000;
k2 = 45000;
c2 = 450;
Po_2 = 10000;
phi_2 = pi/2;
grav =386;
m1 = W1/grav;
m2 = W2/grav;
fprintf('The Mass calculated for 1st system m1=%4.4f lb*s^2/in \n', m1);
fprintf('The Mass calculated for 1st system m2=%4.4f lb*s^2/in \n', m2);
% TIME SPAN
N = 101;
time = linspace(0,50*pi,N);
t_span = [0 4*pi];
% INITIAL DISPLACEMENT
x_o =[0;0;0;0];
%FORCING FUNCTION
P_1 =Po_1*sin(W_bar*time-phi_1);
P_2 =Po_2*sin(W_bar*time-phi_2);
% USING ODE45
[t,x] =ode45(@dx,t_span,x_o,[],m1,m2,k1,k2,c1,c2,time,P_1,P_2);
When I execute it, an error pops up showing as "Attempted to access x(2); index out of bounds because numel(x)=1".
I need to get all the x(1), x(2), x(3), x(4) values. Could anyone help me in this regard..?

Answers (1)

Titus Edelhofer
Titus Edelhofer on 13 Nov 2014
Hi,
you will need to change the order of variables: your function dx should look like
function dx = dx(t, x, m1, m2, ...)
Titus
PS: Personally I would not recommend to name the output like the function name, but it's not wrong.
  2 Comments
Vashish
Vashish on 23 Nov 2014
Hi Titus, Would you be able to give more information on why changing the variables' order would give such a result? I'm having similar problems and I'd like to know in what way should I rearrange my variables.
Thanks, VashishS
Titus Edelhofer
Titus Edelhofer on 24 Nov 2014
That's a requirement from the ode solver. The ode solver does not "look" into the function to find out, which parameter does what. It always assumes the function to be of kind
function dx = myfun(t, x, param1, param2, ...)
where of course dx, t, and x may have names as they like, I just named the variables to express what they represent.
Titus

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!