%% Cholesky Factor of Sparse Matrix
% Calculate the Cholesky factor of a sparse matrix, and use the permutation output to create a Cholesky factor with fewer nonzeros.
%
% Create a sparse positive definite matrix based on the west0479 matrix.

load west0479
A = west0479;
S = A'*A;

%
% Calculate the Cholesky factor of the matrix two different ways. First specify two outputs, and then specify three outputs to enable row and column reordering.

[R,flag] = chol(S);
[RP,flagP,P] = chol(S);

%
% For each calculation, check that flag = 0 to confirm the calculation is successful.

if ~flag && ~flagP
    disp('Factorizations successful.')
else
    disp('Factorizations failed.')
end

%
% Compare the number of nonzeros in chol(S) vs. the reordered matrix chol(P'*S*P). Best practice is to use the three output syntax of chol with sparse matrices, since reordering the rows and columns can greatly reduce the number of nonzeros in the Cholesky factor.

subplot(1,2,1)
spy(R)
title('Nonzeros in chol(S)')
subplot(1,2,2)
spy(RP)
title('Nonzeros in chol(P''*S*P)')

%
% Copyright 2018 The MathWorks, Inc.