# Source code for naginterfaces.​library.​examples.​correg.​corrmat_nearest_ex

```#!/usr/bin/env python
"``naginterface.library.correg.corrmat_nearest`` Python Example."

# pylint: disable=invalid-name

import numpy as np

from naginterfaces.library import correg

[docs]def main():
"""
Example for :func:`naginterfaces.library.correg.corrmat_nearest`.

Find a nearest correlation matrix.

>>> main()
naginterfaces.library.correg.corrmat_nearest Python Example Results.
The Frobenius-nearest correlation matrix to a given square matrix.
Symmetric nearest correlation matrix X:
[
1.00e+00
-8.08e-01,   1.00e+00
1.92e-01,  -6.56e-01,   1.00e+00
1.07e-01,   1.92e-01,  -8.08e-01,   1.00e+00
]
"""

print(
'naginterfaces.library.correg.corrmat_nearest Python Example Results.'
)
print('The Frobenius-nearest correlation matrix to a given square matrix.')

g = np.array([
[2.0, -1.0, 0.0, 0.0],
[-1.0, 2.0, -1.0, 0.0],
[0.0, -1.0, 2.0, -1.0],
[0.0, 0.0, -1.0, 2.0],
])
x = correg.corrmat_nearest(g).x
print('Symmetric nearest correlation matrix X:')
print('[')
for i in range(x.shape[0]):
print('  ' + ', '.join(['{:10.2e}']*(i+1)).format(*x[i, :(i+1)]))
print(']')

if __name__ == '__main__':
import doctest
import sys
sys.exit(
doctest.testmod(
None, verbose=True, report=False,
optionflags=doctest.REPORT_NDIFF,
).failed
)
```