Find the nearest correlation matrix in the Frobenius norm for a given nonpositive semidefinite matrix.

Specify an `N`

-by-`N`

symmetric matrix with all elements in the interval `[-1, 1]`

and unit diagonal.

Compute the eigenvalues of `A`

using `eig`

.

ans = *5×1*
-0.1244
0.3396
1.0284
1.4457
2.3107

The smallest eigenvalue is less than `0`

, which indicates that `A`

is not a positive semidefinite matrix.

Compute the nearest correlation matrix using `nearcorr`

with the default Newton algorithm.

B = *5×5*
1.0000 0.0372 0.0100 -0.0219 -0.8478
0.0372 1.0000 -0.5449 -0.3757 -0.4849
0.0100 -0.5449 1.0000 -0.0381 0.0996
-0.0219 -0.3757 -0.0381 1.0000 0.4292
-0.8478 -0.4849 0.0996 0.4292 1.0000

Compute the eigenvalues of `B`

.

ans = *5×1*
0.0000
0.3266
1.0146
1.4113
2.2475

All of the eigenvalues are greater than or equal to `0`

, which means that `B`

is a positive semidefinite matrix.

When you use `nearcorr`

, you can specify the alternating projections algorithm by setting the name-value pair argument `'method'`

to `'projection'`

.

ans = *5×5*
1.0000 0.0372 0.0100 -0.0219 -0.8478
0.0372 1.0000 -0.5449 -0.3757 -0.4849
0.0100 -0.5449 1.0000 -0.0381 0.0996
-0.0219 -0.3757 -0.0381 1.0000 0.4292
-0.8478 -0.4849 0.0996 0.4292 1.0000

You can also impose elementwise weights by specifying the `'Weights'`

name-value pair argument. For more information on elementwise weights, see Weights.

ans = *5×5*
1.0000 0.0014 0.0287 -0.0222 -0.8777
0.0014 1.0000 -0.4980 -0.7268 -0.4567
0.0287 -0.4980 1.0000 -0.0358 0.0878
-0.0222 -0.7268 -0.0358 1.0000 0.4465
-0.8777 -0.4567 0.0878 0.4465 1.0000

In addition, you can impose `N`

-by-`1`

vectorized weights by specifying the `'Weights'`

name-value pair argument. For more information on vectorized weights, see Weights.

W = *5×1*
0.1000
0.0775
0.0550
0.0325
0.0100

C = *5×5*
1.0000 0.0051 0.0021 -0.0056 -0.8490
0.0051 1.0000 -0.5486 -0.3684 -0.4691
0.0021 -0.5486 1.0000 -0.0367 0.1119
-0.0056 -0.3684 -0.0367 1.0000 0.3890
-0.8490 -0.4691 0.1119 0.3890 1.0000

Compute the eigenvalues of `C`

.

ans = *5×1*
0.0000
0.3350
1.0272
1.4308
2.2070

All of the eigenvalues are greater than or equal to `0`

, which means that `C`

is a positive semidefinite matrix.