%% Solving a Transcendental Equation by Recursion
%
% We want to find a solution for the transcendental equation
% x = \cos \big(x\big)
% The key idea is transforming the equation by recursion, obtaining a succession that is converging to the solution
% x_{n} = \cos \big(x_{n-1} \big) \; \Longrightarrow \; \big\{ x_1\,,\; x_2\,,\; \ldots x_n\,,\; \ldots \big\}
% where
% \displaystyle lim_{n \to \infty} \,x_n = \bar x \;:\quad \bar x = \cos \big( \bar x \big)
%

% 1st approach
tic % <-- what does this command? try "help tic"
x = zeros(1,20); x(1) = pi/4; % initial guess
n = 1; d = 1;
 while d > 0.001 & n < 20
    n = n+1; x(n) = cos(x(n-1));
    d = abs( x(n) - x(n-1) );
end
[n,x(n)]
toc % <-- what does this command? try "help toc"

%
% A more efficient approach (allocating less RAM to store the intermediate results)

% 2nd approach
tic
 xold = pi/4; n = 1; d = 1;
 while d > 0.001 & n < 20
    n = n+1; xnew = cos(xold);
    d = abs( xnew - xold );
    xold = xnew;
end
[n, xnew, d]
toc