MATLAB/Cookbook/Ordinary differential equations

From Wikiversity
Jump to navigation Jump to search

Numerical code for a single first order ode[edit | edit source]

This has yet to be constructed

Numerical code for a non-stiff system of equations[edit | edit source]

function [] = odeNumericalSolver(~)
%ODENUMERICALSOLVER numerically solves a non-stiff ode.
% It solves and plots the ode associated with an object falling under high 
% Reynolds number air drag.  

% It can be reconfigured if this function is to be called (i.e., if it is
% to be called to return Y and T)
% There is no need for the next line if this function is to be called:
clc;close all; clear all;
% The following and all other such parameters must be made global because
% the defining function (called odeMat) can take only to input arguments.
global drag; 
drag=.1;
timeRange =[0 1.5]; % zero to one seconds
initCnds = [17*12*2.54/100,0]; 
% initCnds = [17 feet converted to meters, initial velocity]
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[T,Y] = ode45(@odeMat,timeRange,initCnds,options);
figure % Is this needed?
subplot(1,2,1) % (2 rows, 1 column, plot 1)
plot(T,Y(:,1),'.','Markersize',10);
grid;
title('position versus time');%
subplot(1,2,2) % (2 rows, 1 column, plot 2)
plot(T,Y(:,2),'.','Markersize',10);
grid;
title('velocity versus time');%
end
%%%%%%%%%%
function dq = odeMat(t,q)
% q = [x v]
global drag;
dq = zeros(2,1);    % a column vector
dq(1) = q(2); % dx/dt = v
dq(2) = -9.8 + drag*q(2)^2;
end