%ITERATION METHODS
%(Selcuk Bayin, METU-NCC, bayin@metu.edu.tr)
%Fixed-Point iteration-First try (example 1- Kreyszig)
%f(x)=x^2-3x+1=0
%With x=g(x)=(1/3)(x^2+1)
%With x0=1- Convergent
clc
clear x
x0=1
%%
for n=1:4
    x(1)=x0;
    x(n+1)=(1/3)*(x(n)*x(n)+1);
    rr=x(n+1)-x(n);
end
x,
rr
x(5)
%%
%With x0=2- Still convergent
clc
clear x
x0=2
%%
for n=1:10
    x(1)=x0;
    x(n+1)=(1/3)*(x(n)*x(n)+1);
    rr=x(n+1)-x(n);
end
x
rr
%With x0=3- Divergent
%%
clc
clear x
x0=3
%%
for n=1:4
    x(1)=x0;
    x(n+1)=(1/3)*(x(n)*x(n)+1);
end
x
%Plot of both functions together
%g(x)=(1/3)(x^2+1) and x
%%
fplot(@(x)[x.^(2)-3*x+1,x],[0 3])
%fh = @(x)[x.^(2)-3*x+1,x]
%fh([1;2])
%%
%Fixed-Point iteration-Second try (example 1-Kreyszig)
%f(x)=x*x-3x+1=0
%g(x)=3-1/x
clc
clear x
x0=10
%%
for n=1:8
    x(1)=x0;
    x(n+1)=3-(1/x(n));
    rr=x(n+1)-x(n);
end
x
rr
%%
%Plot of g(x)=3-1/x and x
fplot(@(x)[3-1/x,x],[0.1 5])
fh = @(x)[3-1/x,x] 
%%
%Fixed-Point iteration-first try (example 2- Kreyszig)
%f(x)=x^3+x-1=0
%g(x)=1/(1+x^2)- convergent
clc
clear x
x0=1
%%
for n=1:8
    x(1)=x0;
    x(n+1)=1/(1+x(n)^2);
    rr=x(n+1)-x(n);
end
x
rr
%%
%Plot of g(x) and x
fplot(@(x)[1/(1+x*x),x],[0 1.5])
%fh = @(x)[1/(1+x*x),x]
%%
%Fixed-Point iteration-second try (example 2- Kreyszig)
%f(x)=x^3+x-1=0
%With g(x)=1-x^3- Divergent
clc
clear x
x0=1
%%
for n=1:10
    x(1)=x0;
    x(n+1)=1-x(n)^3;
    rr=x(n+1)-x(n);
end
x
rr
%%
%Plot of g(x) and x
fplot(@(x)[1-x^3,x],[0 1.5])
%fh = @(x)[1-x^3,x]
%fh([1;2])
%%
%Newton's method for f(x)=x^3+x-1=0
%Kreyszig- Example 5
clc
clear x
x0=1
%%
for n=1:3
    x(1)=x0;
    x(n+1)=x(n)-(x(n)^3+x(n)-1)/(3*x(n)^2+1);
    rr=x(n+1)-x(n);
end
x
rr
%%
%Newton's method for f(x)=x-2*sin(x)=0
%Kreyszig- Example 4
clc
clear x
x0=2
%%
for n=1:3
    x(1)=x0;
    N(n)=2*(sin(x(n))-x(n)*cos(x(n)));
    D(n)=1-2*cos(x(n));
    x(n+1)=N(n)/D(n);
    rr=x(n+1)-x(n);
end
x
rr
%%
%SECANT method for f(x)=x-2*sin(x)=0
%Kreyszig- Example 8
clc
clear x
x0=2
x1=1.9
%%
for n=2:3
    x(1)=x0;
    x(2)=x1;
    N(n)=(x(n)-2*sin(x(n)))*(x(n)-x(n-1));
    D(n)=x(n)-x(n-1)+2*(sin(x(n-1))-sin(x(n)));
    x(n+1)=x(n)-N(n)/D(n);
    rr=x(n+1)-x(n);
end
x
rr
%%
%SECANT method for f(x)=x-2*sin(x)=0
%Kreyszig Example 8
clc
clear x
x0=2
x1=1.9
%%
for n=2:3
    x(1)=x0;
    x(2)=x1;
    N(n)=(x(n)-2*sin(x(n)))*(x(n)-x(n-1));
    D(n)=x(n)-x(n-1)+2*(sin(x(n-1))-sin(x(n)));
    x(n+1)=x(n)-N(n)/D(n);
    rr=x(n+1)-x(n);
end
x
rr
%%
%CHALLENGE- DO IT WITH A WHILE LOOP
