Difference between revisions of "MATLAB:Ordinary Differential Equations/Examples"
Line 2: | Line 2: | ||
== Examples == | == Examples == | ||
+ | Note - each example began with the [[MATLAB:Ordinary Differential Equations/Templates|Templates]] provided at this web site. Some comments have been removed from the templates to conserve space while some comments may have been added to provide a clearer explanation of the process for a particular example. | ||
=== Constant Rate of Change === | === Constant Rate of Change === | ||
If the dependent variable has a constant rate of change: | If the dependent variable has a constant rate of change: | ||
Line 157: | Line 158: | ||
\pagebreak | \pagebreak | ||
--> | --> | ||
− | |||
− | |||
== Questions == | == Questions == |
Revision as of 19:38, 25 November 2009
The following examples show different ways of setting up and solving initial value problems in MATLAB. It is part of the page on Ordinary Differential Equations in MATLAB.
Examples
Note - each example began with the Templates provided at this web site. Some comments have been removed from the templates to conserve space while some comments may have been added to provide a clearer explanation of the process for a particular example.
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.