/* nag_correg_corrmat_nearest_rank (g02akc) Example Program.
*
* Copyright 2020 Numerical Algorithms Group.
*
* Mark 27.1, 2020.
*/
#include <math.h>
#include <nag.h>
#include <stdio.h>
int main(void) {
Integer exit_status = 0;
Integer i, j, pdg, pdx, maxit, maxits, n, nsub, rank;
double errtol, f, rankerr, ranktol;
double *g = 0, *x = 0;
/* Nag Types */
Nag_OrderType order;
NagError fail;
INIT_FAIL(fail);
#define G(I, J) g[(J - 1) * pdg + I - 1]
printf(
"nag_correg_corrmat_nearest_rank (g02akc) Example Program Results\n\n");
/* skip heading in data file */
scanf("%*[^\n] ");
/* read in the problem size */
scanf("%" NAG_IFMT "%*[^\n] ", &n);
pdg = n;
pdx = n;
if (!(g = NAG_ALLOC(pdg * n, double)) || !(x = NAG_ALLOC(pdx * n, double))) {
printf("Allocation failure\n");
exit_status = -1;
goto END;
}
/* read in the rank constraint */
scanf("%" NAG_IFMT "%*[^\n] ", &rank);
/* read in the matrix g */
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%lf", &G(i, j));
scanf("%*[^\n] ");
/* use the defaults for errtol , ranktol, maxits, maxit */
errtol = 0.0;
ranktol = 0.0;
maxits = 0;
maxit = 0;
/* nag_correg_corrmat_nearest_rank (g02akc)
* computes the nearest correlation matrix subject to rank constraint
* to a real square matrix using majorized penalty approach of Gao and Sun
*/
nag_correg_corrmat_nearest_rank(g, pdg, n, rank, errtol, ranktol, maxits,
maxit, x, pdx, &f, &rankerr, &nsub, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_correg_corrmat_nearest_rank (g02akc).\n%s\n",
fail.message);
exit_status = 1;
goto END;
}
/* Display results */
order = Nag_ColMajor;
/*
* nag_file_print_matrix_real_gen (x04cac).
* Prints real general matrix
*/
nag_file_print_matrix_real_gen(
order, Nag_GeneralMatrix, Nag_NonUnitDiag, n, n, x, pdx,
"Nearest correlation matrix with rank constraint", NULL, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_file_print_matrix_real_gen (x04cac).\n%s\n",
fail.message);
exit_status = 2;
goto END;
}
printf("\n");
printf(" Number of subproblems solved:%12" NAG_IFMT "\n\n", nsub);
printf(" Squared Frobenius norm of difference: %11.3e\n\n", f);
printf(" Rank error: %37.3e\n\n", rankerr);
END:
NAG_FREE(g);
NAG_FREE(x);
return exit_status;
}