% solutions for examples in MTB week 5

% SL4:
%% 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

% SL18
%% script evaluates two hyperbolic 
%  functions and plot them
close all; clear; clc;

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;

% SL21
%% 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');

% SL22
%% reduction of high values
close all; clear; clc;

x = -(3/2)*pi:pi/100:(3/2)*pi;
y = tan(x);
z = y.*(abs(y) < 1e10);
figure;
plot(x, y);
hold on;
plot(x, z, '--r', 'LineWidth', 2);
axis([-(3/2)*pi, (3/2)*pi, -40, 40]);
legend('Original', 'Omezene hodnoty');
xlabel('x [rad]');
ylabel('tan(x) [-]');

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

% SL34
%% generation of series of coin tossing
close all; clear; clc;
N = 1e4; % number of series
M = 1e3; % number of throws in one set
hody = round(rand(M, N)); % generate numbers (0,1)
noOnesOverAverage = sum(hody) - 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);

% SL35
%% generation of normaly distributed numbers
figure(2);
hist(0 + 15.7743*randn(N,1),-70:2:70);

% SL39
%% 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

% SL40
%% Visualization of approximation of pi
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);

% SL45
%% Fourier series of square signal
close all; clear; clc;
t = -1.1:0.01:1.1;
s = zeros(1, length(t));
T = 1; A = 1;
figure;
hold on; grid on; axis tight;
xlabel('t');
ylabel('s');
for k = 0:10
   s = s + A*4/pi* ...
      sin(2*pi*t*(2*k+1)/T)/(2*k+1);
   plot(t, s);
end


