HOW DO I DO THAT IN MATLAB SERIES?

In this series, I am answering questions that students have asked me about MATLAB. Most of the questions relate to a mathematical procedure.

Contents

TOPIC

How do I solve an initial value ordinary differential equation?

SUMMARY

% Language : Matlab 2020b;
% Authors : Autar Kaw;
% Mfile available at
% http://numericalmethods.eng.usf.edu/blog/ode_initial.m;
% Last Revised : December 22 2020;
% Abstract: This program shows you how to solve an
%           initial value ordinary differential equation.
clc
clear all

INTRODUCTION

disp('ABSTRACT')
disp('   This program shows you how to solve')
disp('   an initial value ordinary differential equation')
disp(' ')
disp('AUTHOR')
disp('   Autar K Kaw of http://autarkaw.wordpress.com')
disp(' ')
disp('MFILE SOURCE')
disp('   http://nm.mathforcollege.com/blog/ode_initial.m')
disp(' ')
disp('LAST REVISED')
disp('   Dec 22 2020')
disp(' ')
ABSTRACT
   This program shows you how to solve
   an initial value ordinary differential equation
 
AUTHOR
   Autar K Kaw of http://autarkaw.wordpress.com
 
MFILE SOURCE
   http://nm.mathforcollege.com/blog/ode_initial.m
 
LAST REVISED
   Dec 22 2020
 

INPUTS

Solve the ordinary differential equation 3y"+5y'+7y=11exp(-x) Define x as a symbol Define y(x)n as a symbol also

syms x y(x)
%The ODE
Dy=diff(y);
ode_eqn=3*diff(y,x,2)+5*diff(y,x,1)+7*y == 11*exp(-13*x);
% The initial conditions
iv_1=Dy(0)==17;
iv_2=y(0)==19;
% The value at which y is sought at
xval=2.0;

DISPLAYING INPUTS

disp('INPUTS')
func=['  The ODE to be solved is ' char(ode_eqn)];
disp(func)
iv_explain=['  The initial conditions are %s' char(iv_1) '    ' char(iv_2)];
disp(iv_explain)
fprintf('  The value of y is sought at x=%g',xval)
disp('  ')
INPUTS
  The ODE to be solved is 7*y(x) + 5*diff(y(x), x) + 3*diff(y(x), x, x) == 11*exp(-13*x)
  The initial conditions are %ssubs(diff(y(x), x), x, 0) == 17    y(0) == 19
  The value of y is sought at x=2  

THE CODE

conds=[iv_1 iv_2];
% Finding the solution of the ordinary differential equation
soln=dsolve(ode_eqn,conds);
soln=simplify(soln);
% vpa below uses variable-precision arithmetic (VPA) to compute each
% element of soln to 5 decimal digits of accuracy
soln=vpa(soln,5);

DISPLAYING OUTPUTS

disp('  ')
disp('OUTPUTS')
output=['  The solution to the ODE is ' char(soln)];
disp(output)
value=subs(soln,x,xval);
fprintf('  The value of y at x=%g is %g',xval,value)
disp('  ')
  
OUTPUTS
  The solution to the ODE is 0.024499*exp(-13.0*x) + 18.976*exp(-0.83333*x)*cos(1.2802*x) + 25.88*exp(-0.83333*x)*sin(1.2802*x)
  The value of y at x=2 is -0.31176