%% Övning 1

%% uppg 1
f=@(x) tan(x)-x
fprim=@(x) sec(x).^2-1 % or tan(x).^2
x=linspace(0,12,500);
plot(x, f(x)), hold on, grid on, axis([0 12 -10 10])
plot(x, fprim(x), 'r--')

kmax=10; tol=0.5e-4; %tol = 'tolerance'
x0=4.5 % init. approximation
 
for k=1:kmax
    d=f(x0)/fprim(x0);
    x0=x0-d
    if abs(d)<tol; break; end
end

% Man ser tydligt ovan att vissa nollställen hamnar nära kurvans asymptoter.
% För att lättare tillämpa Newtons metod så kan man hitta en funktion med
% samma lösningsmängd:
% tanx - x = 0
% => sinx/cosx - x = 0
% => sinx - xcosx = 0



f=@(x) sin(x) - x.*cos(x)
fprim=@(x) x.*sin(x)

plot(x, f(x), x, fprim(x), '--')
x0=4;
for k=1:kmax
    d=f(x0)/fprim(x0);
    x0=x0-d;
    if abs(d)<tol; break; end
end
k,x0, plot(x0, f(x0), 'ro')

x0=8;
for k=1:kmax
    d=f(x0)/fprim(x0);
    x0=x0-d;
    if abs(d)<tol; break; end
end
k,x0, plot(x0, f(x0), 'ro')

x0=10;
for k=1:kmax
    d=f(x0)/fprim(x0);
    x0=x0-d;
    if abs(d)<tol; break; end
end
k,x0, plot(x0, f(x0), 'ro')

%% Uppg 2
L0=80; %dB
beta=1.15e-3; %attenuation factor
L=@(r) L0-20 .* log10(r)-beta*r
r=linspace(0,1000, 10000);
plot(r, L(r)-20), grid on

res=fzero(@(r)L(r)-20,800) % In order to insert the 20dB offset, the function variables must be explicitly called.

%% Uppg 3
k=5.17;
C=28.3;
x=1;


T=@(x,t) C./sqrt(t).*exp(-(x^2)./(k*t))

t=linspace(0.1,2)

plot(t, T(x,t)), hold on, grid on

x1=fzero(@(t)T(x,t)-20, 0.1);
x2=fzero(@(t)T(x,t)-20, 1.8);

x2-x1

plot([x1 x2], [20 20])

%% Uppg 4
%Integralen kan uttryckas sin(sin(t)) genom variabelsubstitution
%(x=sin(t))

f=@(t)sin(sin(t))
integral(f, 0, pi/2)

%% Uppg 5
a=0;b=6;    n=1000; % grafintervall + antal punkter

x=linspace(a,b,n);
C=zeros(size(x));
S=zeros(size(x));

% Inneficient as it computes from 0 to x(i) each time!
tic
for i=1:length(x)
    C(i)=integral(@(t)cos((pi*t.^2)./2), 0, x(i));
    S(i)=integral(@(t)sin((pi*t.^2)./2), 0, x(i));
end
toc

C=zeros(size(x));
S=zeros(size(x));

% More efficient as it computes only each interval
tic
for k=2:n
    C(k)=C(k-1)+integral(@(t)cos((pi*t.^2)./2), x(k-1), x(k));
    S(k)=S(k-1)+integral(@(t)sin((pi*t.^2)./2), x(k-1), x(k)); 
end
toc




subplot(2,1,1)
plot(x, C, x, S)
legend('C(\chi)', 'S(\chi)')
subplot(2,2,3)
plot(C,S), title('Cornus Spiral'), axis equal






