function ynext = stepRK1_np(h, x, y, fName) k = h * feval(fName, x, y); ynext = y + k;
function s = fn(t, u) s = u;
function s = fnOsc(t, u) s = [u(2); -u(1)];
function demoRK1(tf, nsteps) tstep = tf / nsteps; t = linspace(0, tf, nsteps + 1); u = zeros(size(t)); u(1) = 1.0; for k=1:nsteps u(k+1) = stepRK1_np(tstep, t(k), u(k), 'fn'); end utrue = exp(t); figure(1); plot(t, u, '-r;Euler Forward;', t, utrue, '-g;Exact;'); figure(2); plot(t, utrue - u, '-r;Error;');
function demoOscRK1(tf, nsteps) tstep = tf / nsteps; t = linspace(0, tf, nsteps + 1); xRK = zeros(size(t)); u = [1.0; 0.0]; xRK(1) = u(1); for k=1:nsteps uNext = stepRK1_np(tstep, t(k), u, 'fnOsc'); u = uNext; xRK(k+1) = u(1); end xExact = cos(t); figure(1); plot(t, xRK, '-g;Euler Forward;', t, xExact, '-k;Exact;'); grid on; figure(2); plot(t, xExact - xRK, '-r;Error;'); grid on;