MATLAB:Ordinary Differential Equations/Examples
The following examples show different ways of setting up and solving initial value problems in MATLAB.
Examples
Constant Rate of Change
If the dependent variable has a constant rate of change:
where \(k\) is some constant, you can provide the differential equation
with a function called ConstDiff.m
that contains the code:
function dydt = ConstDiff(t, y, k)
% Differential equation for constant growth
% t is time
% y is the state vector
% k contains any required constants
% dydt must be a column vector
dydt = k(1); % or just k since there is only one
You could calculate answers using this model with the following code
called RunConstDiff.m
,
which assumes there are 100 evenly spaced times between 0 and 10, the
initial value of \(y\) is 6, and the rate of change is 1.2:
clear; format short e
% Set name of file containing derivatives
DiffFileName = 'ConstDiff';
% Set up time span, initial value(s), and constant(s)
% Note: Variables should be in columns
tspan = linspace(0, 10);
yinit = 6;
k = 1.2;
% 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
figure(1); clf
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.