NAG Library Manual, Mark 30.3
Interfaces:  FL   CL   CPP   AD 

NAG CL Interface Introduction
Example description
/* nag_lapackeig_dggglm (f08zbc) Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 *
 * Mark 30.3, 2024.
 */

#include <nag.h>
#include <stdio.h>

int main(void) {

  /* Scalars */
  double rnorm;
  Integer i, j, m, n, p, pda, pdb;
  Integer exit_status = 0;
  NagError fail;
  Nag_OrderType order;
  /* Arrays */
  double *a = 0, *b = 0, *d = 0, *x = 0, *y = 0;

#ifdef NAG_COLUMN_MAJOR
#define A(I, J) a[(J - 1) * pda + I - 1]
#define B(I, J) b[(J - 1) * pdb + I - 1]
  order = Nag_ColMajor;
#else
#define A(I, J) a[(I - 1) * pda + J - 1]
#define B(I, J) b[(I - 1) * pdb + J - 1]
  order = Nag_RowMajor;
#endif

  INIT_FAIL(fail);

  printf("nag_lapackeig_dggglm (f08zbc) Example Program Results\n\n");

  /* Skip heading in data file */
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%" NAG_IFMT "%" NAG_IFMT "%*[^\n] ", &m, &n, &p);

#ifdef NAG_COLUMN_MAJOR
  pda = m;
  pdb = m;
#else
  pda = n;
  pdb = p;
#endif

  /* Allocate memory */
  if (!(a = NAG_ALLOC(n * m, double)) || !(b = NAG_ALLOC(m * p, double)) ||
      !(d = NAG_ALLOC(m, double)) || !(x = NAG_ALLOC(n, double)) ||
      !(y = NAG_ALLOC(p, double))) {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }

  /* Read A, B and D from data file */
  for (i = 1; i <= m; ++i)
    for (j = 1; j <= n; ++j)
      scanf("%lf", &A(i, j));
  scanf("%*[^\n] ");

  for (i = 1; i <= m; ++i)
    for (j = 1; j <= p; ++j)
      scanf("%lf", &B(i, j));
  scanf("%*[^\n] ");

  for (i = 0; i < m; ++i)
    scanf("%lf", &d[i]);
  scanf("%*[^\n] ");

  /* Solve the weighted least squares problem: minimize ||inv(B)*(d - A*x)||
   * (in the 2-norm) using nag_lapackeig_dggglm (f08zbc).
   */
  nag_lapackeig_dggglm(order, m, n, p, a, pda, b, pdb, d, x, y, &fail);

  if (fail.code == NE_NOERROR) {
    /* Print least squares solution, x. */
    printf("Weighted least squares solution\n");
    for (i = 0; i < n; ++i)
      printf(" %11.4f%s", x[i], i % 7 == 6 ? "\n        " : "");

    /* Print residual vector y = inv(B)*(d - A*x). */
    printf("\n");
    printf("%s\n", "Residual vector");
    for (i = 0; i < p; ++i)
      printf(" %11.2e%s", y[i], i % 7 == 6 ? "\n        " : "");

    /* Compute and print the square root of the residual sum of squares using
     * nag_blast_dge_norm (f16rac).
     */
    nag_blast_dge_norm(Nag_ColMajor, Nag_FrobeniusNorm, 1, p, y, 1, &rnorm,
                       &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_blast_dge_norm (f16rac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

    printf("\nSquare root of the residual sum of squares\n %11.2e\n", rnorm);
  } else {
    printf("Error from nag_lapackeig_dggglm (f08zbc).\n%s\n", fail.message);
    exit_status = 1;
  }

END:
  NAG_FREE(a);
  NAG_FREE(b);
  NAG_FREE(d);
  NAG_FREE(x);
  NAG_FREE(y);

  return exit_status;
}