How can I solve ordinary differential equations in MATLAB?
Matlab can numerically solve Ordinary Differential equations using 2 methods.
- ODE23 uses 2nd and 3rd order Runge-Kutta formulas
- ODE45 uses 4th and 5th order Runge-Kutta formulas
What you first need to do is to break your ODE into a system of 1st order equations. For instance,
can be written as,
Now, you need to write a matlab function that takes Y1, Y2, and time as arguments and returns Ydot1 and Ydot2. To do this, create a file using emacs or your own favorite editor that contains the following:
Call this file "myode.m" and save it in a place where matlab knows to look for it (either the directory from which you started matlab or your own /mit/username/matlab/ directory).
Now, the moment we have been waiting for: let's solve this ODE. At the matlab prompt, type:
Note:
To see the results, type:
or,
Here, the solid line corresponds to X (displacement) and the dashed line to Xdot (speed).
Your coefficients to your equations do not have to be constant. They can depend on time. For instance if your oscillator is damped and driven:
Your m-file will look something like this:
You might try experimenting with the coefficients to see what happens.