% solutions for examples in MTB week 5

%% SL5:
% script calculates Pythagorean Theorem
close all; clear; clc;

s1   = 4; % for experiment purposes, choose so-called
s2   = 3; % Pythagorean triangle {3,4,5}
type = 'prep';
switch type
   case 'prep'
      c = sqrt(s1^2 + s2^2)
   case 'od'
      a = sqrt(max(s1,s2)^2 - min(s1,s2)^2)
   otherwise % unknown type
      c = 0, a = 0,
end

%% SL9:
% same as any()

%% SL10:
% same as all(all())

%% SL24
% script evaluates two hyperbolic
%  functions and plot them
x  = linspace(-1, 1, 1e2+1);
f1 = sinh(x);
f2 = cosh(x);
plot(x, f1, 'bs-');
hold on;
plot(x, f2, 'rd--');
ylim([-1.5 1.5]);
legend('f_1(x)=sinh(x)', 'f_2(x)=cosh(x) ', ...
   'Location', 'best');
xlabel('x');
ylabel('f_1(x), f_2(x)');
grid on;

%% SL27
% wrong sampling example

close all; clear; clc;
t1 = -1:0.2:1;
t2 = -1:0.1:1;
t3 = -1:0.01:1;
f1 = t1.*sin(pi/2*(1+20*t1));
f2 = t2.*sin(pi/2*(1+20*t2));
f3 = t3.*sin(pi/2*(1+20*t3));
figure;
hold on; grid on;
plot(t1, f1, 'r');
plot(t2, f2, 'g');
plot(t3, f3, 'b');
legend('0.2', '0.1', '0.01');

%% SL38
% generation of uniform distribution
close all; clear; clc;
L = 1e5;
tosses = ceil(8*rand(1, L));
hist(tosses, 1:8);

%% SL40
% generation of series of coin tossing
close all; clear; clc;
N = 1e4; % number of series
M = 1e3; % number of throws in one set
throws = round(rand(M, N)); % generate numbers (0,1)
noOnesOverAverage = sum(throws) - M/2; % is vector
figure(1);
hist(noOnesOverAverage, -70:2:70);

% economy code
% N = 1e4;
% hist(sum(round(rand(N/10, N))) - (N/10)/2, -70:2:70);

%% SL45:
% Monte Carlo approximation of pi
clear; close all; clc;
N      = round(logspace(1, 5, 10)); % number of shots
hits   = zeros(1, length(N)); % number of hits
my_pi  = zeros(size(N)); % approximations of pi
shots  = 2*rand(N(end), 2) - 1; % generation of shots
R      = hypot(shots(:, 1), shots(:, 2)); % radii

for iShot = 1:length(N)
   hits(iShot)  = sum(R(1:N(iShot)) <= 1);
   my_pi(iShot) = 4*hits(iShot)/N(iShot);
end

%% SL45
% Visualization of approximation of pi
clear; close all; clc;
N      = round(logspace(1, 5, 10)); % number of shots
hits   = zeros(1, length(N)); % number of hits
my_pi  = zeros(size(N)); % approximations of pi
shots  = 2*rand(N(end), 2) - 1; % generation of shots
R      = hypot(shots(:, 1), shots(:, 2)); % radii
 
for iShot = 1:length(N)  
   hits(iShot)  = sum(R(1:N(iShot)) <= 1);
   my_pi(iShot) = 4*hits(iShot)/N(iShot);
end

% plotting
figure;
semilogx(N, my_pi, 'x--', 'linewidth',2);
xlim([N(1) N(end)]);
hold on; grid on;
xlabel('shots','FontSize', 15);
ylabel('approximation of \pi','FontSize', 15);
line([N(1) N(end)],[pi pi],'color','r','linewidth',2);