A MATLAB M-file for the midpoint method can be developed as A MATLAB M-file for the fourth-order RK method can be developed as

200

18.11 A MATLAB M-file for the midpoint method can be developed as

function [t,y] = midpointdydt,tspan,y0,h [t,y] = midpointdydt,tspan,y0,h: uses the midpoint method to integrate an ODE input: dydt = name of the M-file that evaluates the ODE tspan = [ti, tf] where ti and tf = initial and final values of independent variable y0 = initial value of dependent variable h = step size output: t = vector of independent variable y = vector of solution for dependent variable ti = tspan1; tf = tspan2; t = ti:h:tf; n = lengtht; if necessary, add an additional value of t so that range goes from t = ti to tf if tntf tn+1 = tf; n = n+1; end y = y0onesn,1; preallocate y to improve efficiency for i = 1:n-1 hh = ti+1 - ti; k1 = fevaldydt,ti,yi; ymid = yi + k1hh2; k2 = fevaldydt,ti+hh2,ymid; yi+1 = yi + k2hh; end plott,y Here is the test of the solution of Prob. 18.5. First, an M-file holding the differential equation is written as function dp = dpdtt, p dp = 0.0261-p12000p; 201 Then the M-file can be invoked as in [t,p]=midpointdpdt,[1950 2000],2555,5; disp[t,p] 1.0e+003 1.9500 2.5550 1.9550 2.8260 1.9600 3.1163 1.9650 3.4253 1.9700 3.7521 1.9750 4.0953 1.9800 4.4529 1.9850 4.8227 1.9900 5.2021 1.9950 5.5881 2.0000 5.9776 The following plot is generated

18.12 A MATLAB M-file for the fourth-order RK method can be developed as

function [t,y] = rk4dydt,tspan,y0,h [t,y] = rk4dydt,tspan,y0,h: uses the fourth-order Runge-Kutta method to integrate an ODE input: dydt = name of the M-file that evaluates the ODE tspan = [ti, tf] where ti and tf = initial and final values of independent variable y0 = initial value of dependent variable h = step size output: t = vector of independent variable y = vector of solution for dependent variable ti = tspan1; tf = tspan2; t = ti:h:tf; n = lengtht; if necessary, add an additional value of t 202 so that range goes from t = ti to tf if tntf tn+1 = tf; n = n+1; end y = y0onesn,1; preallocate y to improve efficiency for i = 1:n-1 hh = ti+1 - ti; k1 = fevaldydt,ti,yi; ymid = yi + k1hh2; k2 = fevaldydt,ti+hh2,ymid; ymid = yi + k2hh2; k3 = fevaldydt,ti+hh2,ymid; yend = yi + k3hh; k4 = fevaldydt,ti+hh,yend; phi = k1+2k2+k3+k46; yi+1 = yi + phihh; end plott,y Here is the test of the solution of Prob. 18.2. First, an M-file holding the differential equation is written as function dy = dydxx, y dy = 1+2xsqrty; Then the M-file can be invoked as in [x,y] = rk4dydx,[0 1],1,0.1; disp[x,y] 0 1.0000 0.1000 1.1130 0.2000 1.2544 0.3000 1.4280 0.4000 1.6384 0.5000 1.8906 0.6000 2.1904 0.7000 2.5440 0.8000 2.9584 0.9000 3.4410 1.0000 4.0000 The following plot is generated 203

18.13 Note that students can take two approaches to developing this M-file. The first program