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

NAG AD Library Introduction
Example description
/* F08KD_P0W_F C++ Header Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 * Mark 30.0, 2024.
 */

#include <iostream>
#include <dco.hpp>
#include <nag.h>
#include <nagad.h>
#include <nagx04.h>
#include <stdio.h>
#include <string>
using namespace std;

int main()
{
  int               exit_status = 0;
  nag::ad::handle_t ad_handle;
  Integer           ifail = 0;
  NagError          fail;
  INIT_FAIL(fail);

  cout << "F08KD_P0W_F C++ Header Example Program Results\n\n";
  // Skip heading in data file
  string mystr;
  getline(cin, mystr);

  // Read matrix dimensions and algorithmic mode
  Integer m, n, mode;
  cin >> m;
  cin >> n;
  cin >> mode;

  // Allocate arrays containing A and its factorized form, B
  // and the solution X.
  Integer  lda = m, ldu = m, ldvt = n, lwork;
  double * a = 0, *s = 0, *u = 0, *vt = 0, *work = 0;
  Integer *iwork = 0;
  Charlen  lena  = 1;
  a              = new double[m * n];
  s              = new double[m];
  u              = new double[m * m];
  vt             = new double[n * n];
  iwork          = new Integer[8 * n];

  // Read the matrix A, register and copy
  double dd;
  for (int i = 0; i < m; i++)
  {
    for (int j = 0; j < n; j++)
    {
      Integer k = i + j * m;
      cin >> a[k];
    }
  }

  // Use routine workspace query to get optimal workspace.
  double dummy[1];
  lwork = -1;
  ifail = 0;
  nag::ad::f08kd(ad_handle, "A", m, n, a, lda, s, u, ldu, vt, ldvt, dummy,
                 lwork, iwork, ifail);

  lwork = (Integer)dummy[0] + 1;
  work  = new double[lwork];

  //  Compute the singular values and left and right singular vectors
  //  of A (A = U*S*(V**T), m < n)
  ifail = 0;
  nag::ad::f08kd(ad_handle, "A", m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork,
                 iwork, ifail);

  // Print primal solution
  cout.precision(4);
  cout.width(12);
  cout << " ";
  cout << " Singular values:\n";
  for (int i = 0; i < m; i++)
  {
    cout.width(11);
    cout << s[i];
  }

  cout << "\n\n";
  x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, m, m, u, ldu,
         "Left singular vectors by column", 0, &fail);
  cout << "\n";
  x04cac(Nag_ColMajor, Nag_GeneralMatrix, Nag_NonUnitDiag, m, n, vt, ldvt,
         "Right singular vectors by row", 0, &fail);

  delete[] work;
  delete[] a;
  delete[] s;
  delete[] u;
  delete[] vt;
  delete[] iwork;
  return exit_status;
}