V = odeToVectorField( eqn1. eqnN ) converts higher-order differential equations eqn1. eqnN to a system of first-order differential equations, returned as a symbolic vector.
[ V , S ] = odeToVectorField( eqn1. eqnN ) converts eqn1. eqnN and returns two symbolic vectors. The first vector V is the same as the output of the previous syntax. The second vector S shows the substitutions made to obtain V .
Define a second-order differential equation:
d 2 y dt 2 + y 2 t = 3 t .
Convert the second-order differential equation to a system of first-order differential equations.
syms y(t) eqn = diff(y,2) + y^2*t == 3*t; V = odeToVectorField(eqn)
V =
The elements of V represent the system of first-order differential equations, where V[i] = Y i ′ and Y 1 = y . Here, the output V represents these equations:
dY 2 dt = 3 t - t Y 1 2 .
For details on the relation between the input and output, see Algorithms.
When reducing the order of differential equations, return the substitutions that odeToVectorField makes by specifying a second output argument.
syms f(t) g(t) eqn1 = diff(g) == g-f; eqn2 = diff(f,2) == g+f; eqns = [eqn1 eqn2]; [V,S] = odeToVectorField(eqns)
V =
S =
The elements of V represent the system of first-order differential equations, where V[i] = Y i ′ . The output S shows the substitutions being made, S[1] = Y 1 = f , S[2] = Y 2 = diff(f) , and S[3] = Y 3 = g .
Solve a higher-order differential equation numerically by reducing the order of the equation, generating a MATLAB® function handle, and then finding the numerical solution using the ode45 function.
Convert the following second-order differential equation to a system of first-order differential equations by using odeToVectorField .
d 2 y d t 2 = ( 1 - y 2 ) dy dt - y .
syms y(t) eqn = diff(y,2) == (1-y^2)*diff(y)-y; V = odeToVectorField(eqn)
V =
Generate a MATLAB function handle from V by using matlabFunction .
M = matlabFunction(V,'vars','t','Y'>)
M = function_handle with value: @(t,Y)[Y(2);-(Y(1).^2-1.0).*Y(2)-Y(1)]
Specify the solution interval to be [0 20] and the initial conditions to be y ′ ( 0 ) = 2 and y ′ ′ ( 0 ) = 0 . Solve the system of first-order differential equations by using ode45 .
interval = [0 20]; yInit = [2 0]; ySol = ode45(M,interval,yInit);
Next, plot the solution y ( t ) within the interval t = [0 20] . Generate the values of t by using linspace . Evaluate the solution for y ( t ) , which is the first index in ySol , by calling the deval function with an index of 1. Plot the solution using plot .
tValues = linspace(0,20,100); yValues = deval(ySol,tValues,1); plot(tValues,yValues)