MATLAB Answers

0

Using ODE45 to solve two coupled second order ODEs

Asked by Ricardo Machado on 25 Aug 2019 at 3:53
Latest activity Answered by madhan ravi
on 25 Aug 2019 at 5:01
I used the ODE to vector field function to change my 2 coupled 2nd order ODEs to a system of 1st order ODEs.
syms k1 k2 m t x1(t) x2(t) Y
Dx1 = diff(x1);
D2x1 = diff(x1,2);
Dx2 = diff(x2);
D2x2 = diff(x2,2);
Eq1 = D2x1 == (-(k1+k2)*x1+(k2)*x2)/m
Eq2 = D2x2 == ((k2*x1)+((k1+k2)*x2))/m
[V,Subs] = odeToVectorField(Eq1, Eq2)
ftotal = matlabFunction(V, 'Vars',{t,Y,k1,k2,m})
It generated this
ftotal =
function_handle with value:
@(t,Y,k1,k2,m)[Y(2);((k1+k2).*Y(1)+k2.*Y(3))./m;Y(4);-((k1+k2).*Y(3)-k2.*Y(1))./m]
However, when I tried to use ODE45 to solve it, i got errors. The initial conditions are x(0)= (1 0)' and ẋ(0)= (0 0)'
tspan = [0 20];
y0 = [1 0; 0 0];
[T,Y] = ode45(ftotal,tspan,y0)
plot(T,Y)
grid
Any help would be appreciated.
Thank you

  1 Comment

k1 , k2 and m values should be numeric.

Sign in to comment.

1 Answer

Answer by madhan ravi
on 25 Aug 2019 at 5:01
 Accepted Answer

syms x1(t) x2(t) k1 k2 m
Dx1 = diff(x1);
D2x1 = diff(x1,2);
Dx2 = diff(x2);
D2x2 = diff(x2,2);
Eq1 = D2x1 == (-(k1+k2)*x1+(k2)*x2)/m;
Eq2 = D2x2 == ((k2*x1)+((k1+k2)*x2))/m;
[V,Subs] = odeToVectorField(Eq1, Eq2);
ftotal = matlabFunction(V, 'Vars',{'t','Y','k1','k2','m'});
% ^-^ - single quotes
interval = [0 20];
y0 = [1 0; 0 0]; %initial conditions
% v-k2
ySol = ode45( @(t,Y)ftotal(t,Y,1,1,1),interval,y0);
% k1-^ m-^
tValues = linspace(interval(1),interval(2),1000);
yValues = deval(ySol,tValues,1); %number 1 denotes first solution likewise you can mention 2 ,3 & 4 for the next three solutions
plot(tValues,yValues)

  0 Comments

Sign in to comment.