function x = cramer(A,b)
% Function to implement Cramer's Rule in the solution of Ax=b
% 
% A is a matrix with dimension n x n
% b is a vector with dimension n x 1
% xs is the solution vector with dimension n x 1 
%
% Syntax:
% xs = cramer(A,b);

[rA,cA] = size(A);  % Determine the size of A
[rb,cb] = size(b);  % Determine the size of b

% Input checks
if rA ~= cA
    disp('Error: A is not a square matrix')
    return
end
if cb ~= 1
    disp('Error: b is not a column vector')
    return
end
if cA ~= rb
    disp('Error: Matrix and vector dimensions are not compatible')
    return
end
dA = det(A);
if dA == 0
    disp('Error: Matrix is singular')
    return
end

x = zeros(rb,1);    % Initialize x
% Main Loop
for i = 1:cA
    if i == 1
        Di = [b A(:,2:cA)];
    elseif i < cA
        Di = [A(:,1:i-1) b A(:,i+1:cA)];
    else
        Di = [A(:,1:i-1) b];
    end
    x(i) = det(Di)/dA;
end