I'm working in MATLAB and I have a problem with a system of differential equations. My system is dvdt = (-2*T)-4*v
and dTdt = 6*T+v
and I want to resolve it using Runge-Kutta of 4th order. I wrote the following code:
If I run only the function odefun
, my code works! But my code didn't work if I run the complete program:
clear all
yy=@(t,y)[dvdt;dTdt]
[t,y]= ode45(@(t,y)yy,[0 1.5],[1 1/2 ]);
function res = odefun(t , y )
% i define two variable i will use: v and TT
v = y(1,:);
T = y(2,:);
% i define the two partial derivative:
res(1,:) = dvdt
res(2,:) = dTdt
dvdt = (-2*T)-4*v
dTdt = 6*T+v;
end
This is my results. I don't know to write a vector of a correct length:
Error using odearguments (line 95) @(T,Y)YY returns a vector of length 1, but the length of initial conditions vector is 2. The vector returned by @(T,Y)YY and the initial conditions vector must have the same number of elements.
Error in ode45 (line 115) odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in sys_ode (line 4) [t,y]= ode45(@(t,y)yy,[0 1.5],[1 1/2 ]);
y
as passed from ode45 to odefun is a flat, one-dimensional array. Your variable assignment like you were dealing with a 2-dimensional array makes no sense. It should be v=y(1); T=y(2);
.
In a code block, you need to observe causality. You need to declare/define a variable before you can use it in another code line.
Without calling odefun you will not get an error as each line in odefun is syntactically correct. However you get an error in its execution as the semantic is wrong.
Try
clear all
[t,y]= ode45(odefun,[0 1.5],[1 1/2 ]);
function res = odefun(t , y )
% i define two variable i will use: v and T
v = y(1);
T = y(2);
% i define the two derivatives:
dvdt = (-2*T)-4*v
dTdt = 6*T+v;
res = [ dvdt dTdt ]
end