Example description
/* nag_nearest_correlation (g02aac) Example Program.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.2, 2017.
 */
/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg02.h>

int main(void)
{
  /* Integer scalar and array declarations */
  Integer exit_status = 0;
  Integer feval, i, iter, j, maxit, maxits, n;
  Integer pdg, pdx;

  /* Double scalar and array declarations */
  double errtol, nrmgrd;
  double *g = 0, *x = 0;
  Nag_OrderType order;
  NagError fail;

  INIT_FAIL(fail);

#ifdef NAG_COLUMN_MAJOR
#define G(I, J) g[(J-1)*pdg + I-1]
#define X(I, J) x[(J-1)*pdx + I-1]
  order = Nag_ColMajor;
#else
#define G(I, J) g[(I-1)*pdg + J-1]
#define X(I, J) x[(I-1)*pdx + J-1]
  order = Nag_RowMajor;
#endif

  printf("nag_nearest_correlation (g02aac) 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 matrix g */
  for (i = 1; i <= n; i++)
    for (j = 1; j <= n; j++)
      scanf("%lf", &G(i, j));
  scanf("%*[^\n] ");

  /* Set up method parameters */
  errtol = 1.00e-7;
  maxits = 200;
  maxit = 10;

  /*
   * nag_nearest_correlation (g02aac)
   * Computes the nearest correlation matrix to a real square matrix,
   * using the method of Qi and Sun
   */
  nag_nearest_correlation(order, g, pdg, n, errtol, maxits, maxit, x, pdx,
                          &iter, &feval, &nrmgrd, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_nearest_correlation (g02aac).\n%s\n",
           fail.message);
    exit_status = 1;
    goto END;
  }
  printf("     Nearest Correlation Matrix\n");
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= n; j++)
      printf("%11.5f%s", X(i, j), j % 4 ? " " : "\n");
  }
  printf("\n");
  printf("\n");
  printf(" Number of Newton steps taken:%11" NAG_IFMT "\n", iter);
  printf(" Number of function evaluations:%9" NAG_IFMT "\n", feval);
  if (nrmgrd > errtol)
    printf(" Norm of gradient of last Newton step: %12.3e\n", nrmgrd);
  printf("\n");

END:
  NAG_FREE(g);
  NAG_FREE(x);

  return exit_status;
}