%Esercizio n.1 del 22 ottobre
function [x, u] = NonLinearShootingNewtonExercise(N, s0, tol)
% Shooting method using Newton's method
% Equation:
% -y''+exp(-x)/2(y'^2+y^2)=exp(-x)/2+cos(x)+2sin(x)
% BC:
% 2y(0)-y'(0)=0
% y(pi)=exp(pi)
% Exact solution:
% y=exp(x)+sin(x)
% Input
% N: number of discretization points
% s0: initial value of s
% tol: tolerance
% Output:
% x: Vector containing the points at which the solution is approximated
% u: Approximated solution
% For testing
% [x, u] = NonLinearShootingNewtonExercise(20, 1, 0.0001);
% y = exp(x) + sin(x);
% plot(x, u, 'r*', x, y, 'k-')
esponenzialepi = exp(pi);
h = pi / N;
x = 0:h:pi;
ds = 1 + tol;
sk = s0;
while ds >= tol
[xx, uvUV] = ode23(@fun, x, [sk 2*sk 1 2]);
phik = uvUV(N+1, 1) - esponenzialepi;
dphik = uvUV(N+1, 3) ; % derivative of phi
skp1 = sk - phik / dphik;
ds = abs(skp1 - sk);
sk = skp1;
end
u = uvUV(:, 1);
u(end) = exp(pi); % Set the boundary condition at x=pi
end
function uvp = fun(x, uvUV)
u = uvUV(1);
v = uvUV(2);
du = uvUV(3);
dv = uvUV(4);
uvp = [v; ...
(exp(-x) / 2 * (v^2 + u^2)) - exp(-x) / 2 - cos(x) - 2 * sin(x); ...
dv; ...
(exp(-x) * u * du) + (exp(-x) * v * dv)];
end