How to use 'if else' in this case?
Afficher commentaires plus anciens
I have the following variance-covariance matrix which is not positive definite:
x = [183.5310 -0.4098 8.0035 -0.0333 -0.1818 -0.9685 0.2681 0.1241 -8.3334;
-0.4098 2.5004 0.7254 0.0150 0.2729 0.0262 0.0390 -0.0128 -0.5049;
8.0035 0.7254 163.7246 -0.0541 -1.1285 0.8830 -0.0161 -0.2604 -0.5571;
-0.0333 0.0150 -0.0541 0.0060 -1.4514 -2.4601 0.0049 -0.0071 -0.0297;
-0.1818 0.2729 -1.1285 -1.4514 -318.8469 -607.2140 -0.0163 -1.7903 -1.4473;
-0.9685 0.0262 0.8830 -2.4601 -607.2140 -924.7691 -0.1620 -2.8692 -1.1332;
0.2681 0.0390 -0.0161 0.0049 -0.0163 -0.1620 0.0772 -0.0070 -0.0476;
0.1241 -0.0128 -0.2604 -0.0071 -1.7903 -2.8692 -0.0070 0.0076 -0.0175;
-8.3334 -0.5049 -0.5571 -0.0297 -1.4473 -1.1332 -0.0476 -0.0175 21.2720]
I can correct it and make it positive definite in this way:
[V,D] = eig(x); % Calculate the eigendecomposition of your matrix (A = V*D*V')
% where "D" is a diagonal matrix holding the eigenvalues of your matrix "A"
d= diag(D); % Get the eigenvalues in a vector "d"
d(d <= 1e-7) = 1e-7; % Set any eigenvalues that are lower than threshold "TH" ("TH" here being
% equal to 1e-7) to a fixed non-zero "small" value (here assumed equal to 1e-7)
D_c = diag(d); % Built the "corrected" diagonal matrix "D_c"
PphiTilde = V*D_c*V'; % Recalculate your matrix "A" in its PD variant "A_PD"
Yet, I would like to write a code that says: if the matrix is not positive definite then do what I did above. I tried unsuccessfully:
if chol(x) == 'Matrix must be positive definite.'
[V,D] = eig(x); % Calculate the eigendecomposition of your matrix (A = V*D*V')
% where "D" is a diagonal matrix holding the eigenvalues of your matrix "A"
d= diag(D); % Get the eigenvalues in a vector "d"
d(d <= 1e-7) = 1e-7; % Set any eigenvalues that are lower than threshold "TH" ("TH" here being
% equal to 1e-7) to a fixed non-zero "small" value (here assumed equal to 1e-7)
D_c = diag(d); % Built the "corrected" diagonal matrix "D_c"
PphiTilde = V*D_c*V'; % Recalculate your matrix "A" in its PD variant "A_PD"
else x
end
Can anyone help me?
Thanks!
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!