%clear;
%Filip Olejnik, 3ZIJ1A, 1. rocnik, 2. stupen, (sme len jeden kruzok)

%IMPORT DAT
tic
X = load("data01.txt");
X = sort(X);

%VYPOCTY STLPCOV 
N = length(X);
k = 7;
Xmax = X(end);
Xmin = X(1);

R = Xmax - Xmin;

h = ceil(R/k*1000)/1000;

K1 = fixed.Interval(Xmin, Xmin+h, "[)");
K2 = fixed.Interval(Xmin+h, Xmin+h*2, "[)");
K3 = fixed.Interval(Xmin+h*2, Xmin+h*3, "[)");
K4 = fixed.Interval(Xmin+h*3, Xmin+h*4, "[)");
K5 = fixed.Interval(Xmin+h*4, Xmin+h*5, "[)");
K6 = fixed.Interval(Xmin+h*5, Xmin+h*6, "[)");
K7 = fixed.Interval(Xmin+h*6, Xmin+h*7, "[)");

K = [K1 K2 K3 K4 K5 K6 K7];


Xj = zeros(1,k);
for j = 1:length(K)
    Xj(j) = (K(j).LeftEnd + K(j).RightEnd)/2;
end

nj = zeros(1,k);

for i=1:N    
    if X(i) < K(1).RightEnd
        nj(1) = nj(1) + 1;    
    elseif X(i) < K(2).RightEnd
        nj(2) = nj(2) + 1;
    elseif X(i) < K(3).RightEnd
        nj(3) = nj(3) + 1;
    elseif X(i) < K(4).RightEnd
        nj(4) = nj(4) + 1;
    elseif X(i) < K(5).RightEnd
        nj(5) = nj(5) + 1;
    elseif X(i) < K(6).RightEnd
        nj(6) = nj(6) + 1;
    elseif X(i) < K(7).RightEnd
        nj(7) = nj(7) + 1;       
    end   
end

Pj = zeros(1,k);
for i = 1:length(Pj)
    Pj(i) = nj(i)/N;
end

Nj = zeros(1,k);
for i=1:k
    for j=1:i
        Nj(i) = Nj(i) + nj(j);
    end
end

Mj = zeros(1, k);
for i=1:k
    Mj(i) = Nj(i)/N;
end

%TABULKA

interval = [
    "[" + Xmin + "; " + (Xmin+h) + ")"
    "[" + (Xmin+h) + "; " + (Xmin+h*2) + ")"
    "[" + (Xmin+h*2) + "; " + (Xmin+h*3) + ")";
    "[" + (Xmin+h*3) + "; " + (Xmin+h*4) + ")";
    "[" + (Xmin+h*4) + "; " + (Xmin+h*5) + ")";
    "[" + (Xmin+h*5) + "; " + (Xmin+h*6) + ")";
    "[" + (Xmin+h*6) + "; " + (Xmin+h*7) + ")"
];

Xj = Xj';
nj = nj';
Pj = Pj';
Nj = Nj';
Mj = Mj';

tabulka = table(interval, Xj, nj, Pj, Nj, Mj);
disp(tabulka)

%Bodovo odhadnutá stredná hodnota

E = 0;
for i = 1:k
    E = E + (Xj(i)*nj(i));
end
E = E/N;
disp("Bodovo odhadnutá stredná hodnota: " + E);

%Bodovo odhadnutý rozptyl
D = 0;
for i=1:k
    D = D + ((Xj(i) - E)^2)*nj(i);
end
D = D*(1/(N-1));
disp("Bodovo odhadnutý rozptyl: " + D);

%Smerodajná odchýlka
SmerOdch = sqrt(D);
disp("Smerodajná odchýlka: " + SmerOdch);

%Intervalový odhad pre strednú hodnotu
u = 1.96; %tabulka
n = N;

E1 = E - (SmerOdch/sqrt(n)) * u;
E2 = E + (SmerOdch/sqrt(n)) * u;

IntervalStredHod = "S 95% pravdepodobnosťou intervalový odhad pre strednú hodnotu patrí do intervalu [" + E1 + "; " + E2 + "]";
disp(IntervalStredHod);

%Interval spolahlivosti pre rozptyl
X21 = chi2inv(0.975, n);
X22 = chi2inv(0.025, n);

D1 = ((n-1)*D)/X21;
D2 = ((n-1)*D)/X22;

IntervalSpolahlivosti = "Interval spolahlivosti pre rozptyl patrí do intervalu [" + D1 + "; " + D2 + "]";
disp(IntervalSpolahlivosti);

toc