function newton_demo(examples)
% Plot Newton examples 1--3, for example newton_demo(1:3).

% Define three example problems.
f = {@(x) x.^2 - 2, @(x) cos(x) - x, @(x) x.^3 - 2 * x - 5};
df = {@(x) 2 * x, @(x) -sin(x) - 1, @(x) 3 * x.^2 - 2};
pstart = [1, 1, 2];
xlimits = [0, 2; 0, 1; 1, 3];
names = {'x^2 - 2', 'cos(x) - x', 'x^3 - 2x - 5'};

% Plot the selected examples.
for example = examples
    xmin = xlimits(example, 1);
    xmax = xlimits(example, 2);
    x = linspace(xmin, xmax, 1000);

    figure
    plot(x, f{example}(x), 'LineWidth', 2)
    hold on
    plot([xmin, xmax], [0, 0], 'k', 'LineWidth', 1.5)

    % Compute and plot five Newton iterations.
    p0 = pstart(example);
    for n = 1:5
        p = p0 - f{example}(p0) / df{example}(p0);
        plot([p0, p0], [0, f{example}(p0)], 'r', 'LineWidth', 1.5)
        plot([p0, p], [f{example}(p0), 0], 'r', 'LineWidth', 1.5)
        plot(p0, f{example}(p0), '.r', 'MarkerSize', 16)
        p0 = p;
    end

    title(names{example})
    xlim([xmin, xmax])
    grid on
end
