%% Week 2 -- Computational Tools for Macroeconomics using MATLAB
%% In class examples

%%%%%%%%%%%%%%%%%%
clear; close; clc;

GDP0=1;
g=0.01;
GDP(1) = GDP0;
for t = 2:10
    GDP(t) = GDP(t-1) * (1+g);
end

%%%%%%%%%%%%%%%%%%
clear; close; clc;

x = 5; y = 10;
(x < y) & (y < 20)   % true
~(x == y)            % true

%%%%%%%%%%%%%%%%%%
clear; close; clc;

x = 5;
y = 0;

if (y ~= 0) && (x/y > 1)
    disp('True')
else
    disp('False')
end

%%%%%%%%%%%%%%%%%%
clear; close; clc;

GDP0=1;
g=0.01;
GDP(1) = GDP0;
for t = 2:10
    GDP(t) = GDP(t-1) * (1+g);
end

g = 100 * (GDP(2:end)./GDP(1:end-1) - 1);  % percent growth
lab = strings(size(g));
for t = 1:numel(g)
    if g(t) > 0
        lab(t) = "Expansion";
    elseif g(t) < 0
        lab(t) = "Contraction";
    else
        lab(t) = "Flat";
    end
end

%%%%%%%%%%%%%%%%%%
clear; close; clc;

N = 10;
sq = zeros(1, N);        % preallocate
for i = 1:N
    sq(i) = i^2;
end

disp(sq)   

%%%%%%%%%%%%%%%%%%
clear; close; clc;

N = 10;
F = zeros(1, N);   % preallocate
F(1) = 1; F(2) = 1;

for t = 3:N
    F(t) = F(t-1) + F(t-2);
end

disp(F)


%%%%%%%%%%%%%%%%%%
clear; close; clc;

GDP0      = 100;      % initial level
g         = 0.05;     % 5% growth per period
threshold = 200;

GDP = GDP0;
t   = 0;
while GDP < threshold
    GDP = GDP * (1 + g);
    t   = t + 1;
end

fprintf('Reached %.1f after %d periods.\n', GDP, t);


%%%%%%%%%%%%%%%%%%
clear; close; clc;


rng(123);                 % reproducibility
x = rand(1e6,1);          % 1 million draws

% Loop sum
tic
s1 = 0;
for i = 1:numel(x)
    s1 = s1 + x(i);
end
t_loop = toc;

% Vectorised sum
tic
s2 = sum(x);
t_vec = toc;

fprintf('loop: %.4fs | vectorised: %.4fs | diff = %.3g\n', ...
        t_loop, t_vec, abs(s1-s2));