%% fig_newton_frames.m
% Export PNG frames for Newton (alpha=1) and damped Newton (alpha=0.5)

f  = @(x) x.^3 - 5*x + 1;
fp = @(x) 3*x.^2 - 5;

% Paths
x0 = 1.5; maxit = 10; tolF = 1e-8;
xs_full = newton_path(x0, 1.0, f, fp, maxit, tolF);
xs_damp = newton_path(x0, 0.5, f, fp, maxit, tolF);

x = linspace(0, 5, 400); y = f(x);
ylimVals = [-25 25];

% --- Undamped frames
for k = 1:numel(xs_full)
    figure('Color','w'); hold on; grid on; box on;
    plot(x, y, 'b', 'LineWidth', 1.5); yline(0,'k','LineWidth',1);

    % Plot tangent at current point (except k==numel)
    xt = xs_full(k);
    ft = f(xt); fpt = fp(xt);
    plot(xs_full(1:k), f(xs_full(1:k)), 'o-','LineWidth',1.2,'DisplayName','Path');

    % Tangent line (local linearization)
    xv = linspace(xt-0.8, xt+0.8, 50);
    tv = ft + fpt*(xv - xt);
    plot(xv, tv, 'g--', 'LineWidth', 1);

    ylim(ylimVals); xlabel('x'); ylabel('f(x)');
    title(sprintf('Newton (\\alpha=1): iteration %d', k));
    exportgraphics(gcf, sprintf('newton_full_iter%d.png', k), 'Resolution', 300);
    close(gcf);
end

% --- Damped frames
for k = 1:numel(xs_damp)
    figure('Color','w'); hold on; grid on; box on;
    plot(x, y, 'b', 'LineWidth', 1.5); yline(0,'k','LineWidth',1);

    xt = xs_damp(k);
    ft = f(xt); fpt = fp(xt);
    plot(xs_damp(1:k), f(xs_damp(1:k)), 's--','LineWidth',1.2,'DisplayName','Path');

    xv = linspace(xt-0.8, xt+0.8, 50);
    tv = ft + fpt*(xv - xt);
    plot(xv, tv, 'm--', 'LineWidth', 1);

    ylim(ylimVals); xlabel('x'); ylabel('f(x)');
    title(sprintf('Damped Newton (\\alpha=0.5): iteration %d', k));
    exportgraphics(gcf, sprintf('newton_damp_iter%d.png', k), 'Resolution', 300);
    close(gcf);
end

% --- Helper (place in separate file newton_path.m if needed)
function xs = newton_path(x0, alpha, f, fp, maxit, tolF)
xs = x0;
for it = 1:maxit
    fx = f(x0); fpx = fp(x0);
    if abs(fpx) < 1e-12, break; end
    x0 = x0 - alpha * fx / fpx;
    xs(end+1) = x0; %#ok<AGROW>
    if abs(f(x0)) < tolF, break; end
end
end