Euler Forward Step (RK1) Demonstration

File stepRK1_np.m
function ynext = stepRK1_np(h, x, y, fName)
    k = h * feval(fName, x, y);
    ynext = y + k;

File fn.m
function s = fn(t, u)
    s = u;

File fnOsc.m
function s = fnOsc(t, u)
    s = [u(2); -u(1)];

File demoRK1.m
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;');

File demoOscRK1.m
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;

Try the following from the Octave command line.