MATLAB:Ordinary Differential Equations/Templates
The code below is a template for creating a script whose job is to solve a system of initial value problems based on ordinary differential equations. Note that it takes advantage of
Flexible Programming in MATLAB such that the name of the function that calculates the actual derivatives is only required in the DiffFileName
variable. This program calls the StatePlotter
program, available at MATLAB:Ordinary Differential Equations/State Plotter.
Contents
Code
% Template for using an ODE solver in MATLAB
% tout and yout will be the time and state variables
% Be sure to change name of file containing derivatives,
% time span, initial values, and any constants, as well
% as setting the flag for whether to make state plots
% Initialize workspace and graph
clear; format short e; figure(1); clf
% Set name of file containing derivatives
DiffFileName = '';
% Set up time span, initial value(s), and constant(s)
% Note: Variables should be in columns
tspan = ;
yinit = ;
k = ;
% Determine if states should be plotted
PlotStates = 1;
%% Under the hood
% Use ODE function of choice to get output times and states
DE = eval(sprintf('@(t, y, k) %s(t,y,k)', DiffFileName))
[tout, yout] = ode45(@(t,y) DE(t,y,k), tspan, yinit);
% Plot results
if PlotStates
StatePlotter(tout, yout)
end
Questions
Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.