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

NAG CL Interface Introduction
Example description
/* nag_lapackeig_zgglse (f08znc) 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 */
  Complex *a = 0, *b = 0, *c = 0, *d = 0, *x = 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_zgglse (f08znc) 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 = p;
#else
  pda = n;
  pdb = n;
#endif

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

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

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

  for (i = 1; i <= m; ++i)
    scanf(" ( %lf , %lf )", &c[i - 1].re, &c[i - 1].im);
  scanf("%*[^\n] ");

  for (i = 1; i <= p; ++i)
    scanf(" ( %lf , %lf )", &d[i - 1].re, &d[i - 1].im);
  scanf("%*[^\n] ");

  /* Solve the equality-constrained least squares problem    */
  /* minimize ||c - A*x|| (in the 2-norm) subject to B*x = D */
  nag_lapackeig_zgglse(order, m, n, p, a, pda, b, pdb, c, d, x, &fail);

  if (fail.code == NE_NOERROR) {
    /* Print least squares solution */
    printf("%s\n", "Constrained least squares solution");
    for (i = 1; i <= n; ++i)
      printf("(%7.4f, %7.4f)%s", x[i - 1].re, x[i - 1].im,
             i % 4 == 0 || i == n ? "\n" : " ");

    /* Compute the square root of the residual sum of squares */
    nag_blast_zge_norm(Nag_ColMajor, Nag_FrobeniusNorm, 1, m - n + p, &c[n - p],
                       1, &rnorm, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_blast_zge_norm (f16uac).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }

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

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

  return exit_status;
}