Numerical Computing with MATLAB

Many mathematical models involve more than one unknown function, and second- and higher order derivatives. These models can be handled by making y(t) a vector-valued function of t. Each component is either one of the unknown functions or one of its derivatives. The MATLAB vector notation is particularly convenient here.
For example, the second-order differential equation describing a simple harmonic oscillator
becomes two first-order equations. The vector y(t) has two components, x(t) and its first derivative ![]()
Using this vector, the differential equation is

The MATLAB function defining the differential equation has t and y as input arguments and should return f(t, y) as a column vector. For the harmonic oscillator, the function is an M-file containing
function ydot = harmonic(t,y) ydot = [y(2); -y(1)]
A fancier version uses matrix multiplication in an inline function,
f = inline('[0 1; -1 0]*y','t','y'); or an anonymous function,
f = @(t,y) [0 1; -1 0]*y
In all cases, the variable t has to be included as the first argument, even though it is not explicitly involved in the differential equation.
A slightly more complicated example, the two-body problem, describes the orbit of one body under the gravitational attraction of a much heavier body. Using Cartesian coordinates, u(t) and ?(t), centered in the heavy body, the...