%% Suppress Errors for Nonsymmetric Positive Definite Matrices
% Use chol with two outputs to suppress errors when the input matrix is not symmetric positive definite.
%
% Create a 5-by-5 matrix of binomial coefficients. This matrix is symmetric positive definite, so subtract 1 from the last element to ensure it is no longer positive definite.

A = pascal(5);
A(end) = A(end) - 1

%
% Calculate the Cholesky factor for A. Specify two outputs to avoid generating an error if A is not symmetric positive definite.

[R,flag] = chol(A)

%
% Since flag is nonzero, it gives the pivot index where the factorization fails. chol is able to calculate q = flag-1 = 4 rows and columns correctly before failing when it encounters the part of the matrix that changed.
% Verify that R'*R returns four rows and columns that agree with A(1:q,1:q).

q = flag-1;
R'*R
A(1:q,1:q)

% Copyright 2018 The MathWorks, Inc.