%a)
load m44.dat
A = m44(:);     %zvektorizuje maticu
n = size(A,1);  %urci pocet stlpcov matice
[X,Y] = meshgrid(1:size(m44,1));    %vytvori matice X,Y priradujuce hodnotu x a y pre kazdy prvok matice m44
mesh(X,Y,m44)   %vykresli trojrozmerny graf

%b)
mean(A)     %aritmeticky priemer
median(A)   %median
mode(A)     %modus
sigma = sqrt(sum((A-mean(A)).^2)/(n-1.46))  %standardna odchylka, inak std()
gamma1 = sum((A-mean(A)).^3)/n/sigma^3      %sikmost, inak skewness()
gamma2 = (n+1)/(n-1)*sum((A-mean(A)).^4)/n/sigma^4-3    %spicatost, inak kurtosis()

%c) - median matice A, moze byt vytvoreny aj formou funkcie
A = sortrows(A(:));
if mod(size(A,1),2) == 0
    med = 0.5*A(size(A,1)/2) + 0.5*A(size(A,1)/2+1);
else
    med = A(size(A,1)/2+0.5);
end
med

%c) - modus matice A
A = sortrows(A(:));
B = [];
for i = 1:size(A)-1
    q = 1;
    while A(i) == A(i+q)
        q = q+1;
    end
    B = [B;q];
end
modus = A(find(B==max(B)))

%d)
sigma_r = 1.482*median(abs(A-median(A)))    %robustna odchylka
stars = find(abs(m44-median(A))>3.5*sigma_r);   %vrati vektor suradnic matice m44, v ktorych su odlahle body - hviezdy
noise = m44;
noise(stars) = [];  %odstrani prvky matice noise, kde sa nachadzaju hviezdy
A = noise;
mean(A)
median(A)
mode(A)
sigma = sqrt(sum((A-mean(A)).^2)/(n-1.46))
gamma1 = sum((A-mean(A)).^3)/n/sigma^3
gamma2 = (n+1)/(n-1)*sum((A-mean(A)).^4)/n/sigma^4-3

%e)
stars = find(abs(m44-mean(m44(:)))>5*sigma_r);
peaks = median(A)*ones(size(m44,1));    %vytvori jednotkovu maticu nasobenu medianom
peaks(stars) = m44(stars);  %miesta s vyskytom hviezd nahradi hodnotami matice m44
figure  %otvori nove graficke okno
mesh(X,Y,peaks)

%f)
B = sort(m44(:),'descend');
maxima = [];
for i = 1:30
    [a,b] = find(m44==B(i));    %najde polohy vysokych cisel v matici m44
    maxima = [maxima;a,b];  %vypise suradnice najjasnejsich pixelov
end
maxima

r1 = 4; r2 = 7;     %polomer hviezdy, polomer okolia
Q = m44(a-r1:a+r1,b-r1:b+r1);
Q2 = m44(a-r2:a+r2,b-r2:b+r2);
average = (sum(Q2(:))-sum(Q(:)))/((2*r2+1)^2-(2*r1+1)^2);   %priemerna hodnota okolia
inst_mag = -2.5*log10(sum(Q(:))-(2*r1+1)^2*average)    %instrumentalna jasnost hviezdy