% The code partly from
% https://www.mathworks.com/matlabcentral/fileexchange/47306-determinant-of-matrices-using-the-leibniz-formula-recursively

function d = mydetermin(A)
%MYDETERMIN - calculate determinant of a matrix using recursive calls

% det(A) = sum(a(1,j)*Cj*sign) j=1,n
% Cj is the determinant of the reduced matrix obtained removing 
% the 1st row and the column j of the matrix A
    [n, ~] = size(A);     % number of rows and columns of A
    d = 0;

    if n == 1
        % The base case
        d = A(1,1);
    else
        % Generating a matrix with r-1 rows and columns. 
        % Recursively call the function for the reduced matrix
        temp_A = A;
        temp_A(1,:) = [];         % remove the first row
        sign = 1;
        for i = 1:n
            save_A = temp_A;
            a1i = A(1,i);         % save the element of the 1st row and ith column
            if a1i ~= 0
                temp_A(:,i) = []; % remove the ith column1
                deti = mydetermin(temp_A); % Calculate the determinant of the reduced matrix
                d = d + sign * a1i * deti;
                temp_A = save_A;           % restore 
            end
            sign = -sign;
        end
    end 
end
