%semestralni prace - LU rozklad matice A s castecnym vyberem hlavnich prvku.
%autor 
%VSTUP A - matice 3x3
%      
%VYSTUP dolni 3-uhelnikova matice L, horni 3-uhelnikova matice U, permutacni matice P; matice 3x3

function [L, U, P] = LURozklad(A)

    P = eye(size(A)); % jednotkova matice
    
    L = P;
    
    A_predchozi = A;
    P_predchozi = P;
    
    for k = 1:size(A) - 1
        % urceni indexu "r" pivotniho radku
        r = IndexPivotnihoRadku(A, k, k);
         
        % prohozeni radku k a r matice A_predchozi
        A_predchozi = A;
        A = VymenaRadkuMatice(A, k, r);
        
        % prohozeni radku k a r matice P_predchozi: 
        P_predchozi = VymenaRadkuMatice(P_predchozi, k, r);
        P = P_predchozi;

        for i = k + 1:size(A)
            m_ik = A(i, k)/A(k, k);
            
            for j = k + 1:size(A)
                A(i, j) = A(i, j) - m_ik * A(k, j);
            end
                
            A(i, k) = m_ik;
        end
        
        printf2(k);
        printf('matice A: ', A);
    end

    printf('matice A: ', A);
    
    %sestaveni dolni 3-uhelnikove matice L:
    for i = 2:size(A)
        for j = 1:size(A)
            if i > j
                L(i, j) = A(i, j); % ve skriptech je A_predchozi(i, j); chyba?
            end
        end
    end
                    
    printf('matice L: ', L);
    
    %sestaveni horni 3-uhelnikove matice U:
    for i = 1:size(A)
        for j = 1:size(A)
            if i <= j
                U(i, j) = A(i, j);% ve skriptech je A_predchozi(i, j); chyba?
            end
        end
    end

    printf('matice U: ', U);
                    
    P = P_predchozi;
    
    printf('matice P:', P);
    
end

function [r] = IndexPivotnihoRadku(A, OdRadku, IndexSloupce)
    MaxHodnota = 0;
    for i = OdRadku:size(A)
        if abs(A(i,IndexSloupce)) > MaxHodnota
            MaxHodnota = abs(A(i,IndexSloupce));
            r = i;
        end
end

function [A] = VymenaRadkuMatice(A, radek1, radek2)
    PomocnyRadek = A(radek1,:);
    A(radek1, :) = A(radek2,:);
    A(radek2, :) = PomocnyRadek;    
end

function printf(string, value)
    disp(string);
    disp(value);
end

function printf2(value)
    sprintf('krok c.%d: ', value)
end
