# I have differential equations and I need to write them into a vector function

23 views (last 30 days)
ssmith on 17 Nov 2021
Edited: ssmith on 23 Nov 2021
How do you write the right-hand-sides of the differential equations into a vector function?
Cris LaPierre on 19 Nov 2021

William Rose on 17 Nov 2021
Edited: William Rose on 18 Nov 2021
The documentation for ode45() is really good, I think. Can you make an effort at writing some code, and post what you have so far? You already have both first order differential equations, which means you don;t have to do any more math.
A key concept for this kind of problem is that you define a column vector whose elements are the variables for which you have a first order differential equation. In your problem, you could define the column vector x of length 2, where x(1)=the variable you call y, and x(2)=the variable you call z.
You write a function that receives the current value of x and of time t. It returns the column vector of first derivatives of x. You can save the function as its own .m file, or you can include it at the end of your code, after the last line of code. The ode45() documentation decribes all this. YOur function will look like this:
function dxdt = odefun(t,x)
%Inputs
% x (2x1): x(1)=y, x(2)=z
% t (scalar)
%Output
% dxdt (2x1)
dxdt=zeros(2,1); %make sure dxdt is a column and not a row
dxdt(1)=5 + x(2)/5 - 4*x(1)/(20+3*t);
dxdt(2)=4*x(1)/(20+3*t) - 2*x(2)/5;
end
You'll also need a main program which calls ode45. Again, see the docmentaiton for good examples.
William Rose on 19 Nov 2021
@ssmith, you define a vector x which encompasses all the first order differential equations in your system. In your case you have 2 first order diff eqs: dy/dt and dz/dt. So let's assume that x(1) is what you call y, and x(2) is what you call z. Then the differential equations are and The odefun() which I posted earlier encodes those equations.
In your main, deifne the initial conditions
x0=[0;20];
and the time span of integration
tspan=[0 12];
Then call ode45. I am using a syntax for odefun that assures that teh variables t and x get passed. I honestly thought you could use a simpler synatx, but tonight I am not having success with the simpler syntax, and the following works:
[t,x]=ode45(@(t,x) odefun(t,x),tspan,x0);
ode45() returns a vector t with the times of the solution, from 0 to 12, and it returns an array x with 2 columns: x1 and x2, evaluated at the times listed in vector t. After that you can plot t versus x(:,1) and t versus x(:,2).