%% Compute Determinant of Inverse of Ill-Conditioned Matrix
% Examine how to calculate the determinant of the matrix inverse A^(-1), for an ill-conditioned matrix A, without explicitly calculating A^(-1).
% Create a 10-by-10 Hilbert matrix, A.

A = hilb(10);

%
% Find the condition number of A.

c = cond(A)

% The large condition number suggests that A is close to being singular, so calculating inv(A) might produce inaccurate results. Therefore, the inverse determinant calculation det(inv(A)) is also inaccurate.
%
% Calculate the determinant of the inverse of A by exploiting the fact that
% det\left( A^ {-1} \right) = \frac{1}{det\left(A\right)}

d1 = 1/det(A)

% This method avoids computing the inverse of the matrix, A.
%
% Calculate the determinant of the exact inverse of the Hilbert matrix, A, using invhilb. Compare the result to d1 to find the relative error in d1.

d = det(invhilb(10));
relError = abs(d1-d)/abs(d)

% The relative error in d1 is reasonably small. Avoiding the explicit computation of the inverse of A minimizes it.
%
% For comparison, also calculate the determinant of the inverse of A by explicitly calculating the inverse. Compare the result to d to see the relative error.

d2 = det(inv(A));
relError2 = abs(d2-d)/abs(d)

% The relative error in the calculation of d2 is many orders of magnitude larger than that of d1.
% Copyright 2012 The MathWorks, Inc.