/* nag_dgglse (f08zac) Example Program. * * Copyright 2008 Numerical Algorithms Group. * * Mark 9, 2009. */ #include #include #include #include #include #include int main(int argc, char *argv[]) { FILE *fpin, *fpout; /* 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, *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); fpin = nag_example_file_io(argc, argv, "-data", NULL); fpout = nag_example_file_io(argc, argv, "-results", NULL); fprintf(fpout, "nag_dgglse (f08zac) Example Program Results\n\n"); /* Skip heading in data file */ fscanf(fpin, "%*[^\n] "); fscanf(fpin, "%ld%ld%ld%*[^\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, double)) || !(b = NAG_ALLOC(p*n, double)) || !(c = NAG_ALLOC(m, double)) || !(d = NAG_ALLOC(p, double)) || !(x = NAG_ALLOC(n, double))) { fprintf(fpout, "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) fscanf(fpin, "%lf", &A(i, j)); } fscanf(fpin, "%*[^\n] "); for (i = 1; i <= p; ++i) { for (j = 1; j <= n; ++j) fscanf(fpin, "%lf", &B(i, j)); } fscanf(fpin, "%*[^\n] "); for (i = 1; i <= m; ++i) fscanf(fpin, "%lf", &c[i - 1]); fscanf(fpin, "%*[^\n] "); for (i = 1; i <= p; ++i) fscanf(fpin, "%lf", &d[i - 1]); fscanf(fpin, "%*[^\n] "); /* Solve the equality-constrained least-squares problem */ /* minimize ||c - A*x|| (in the 2-norm) subject to B*x = D */ nag_dgglse(order, m, n, p, a, pda, b, pdb, c, d, x, &fail); if (fail.code == NE_NOERROR) { /* Print least-squares solution */ fprintf(fpout, "%s\n", "Constrained least-squares solution"); for (i = 1; i <= n; ++i) fprintf(fpout, "%11.4f%s", x[i - 1], i%7 == 0 || i == n?"\n":" "); /* Compute the square root of the residual sum of squares */ nag_dge_norm(Nag_ColMajor, Nag_FrobeniusNorm, 1, m - n + p, &c[n - p], 1, &rnorm, &fail); if (fail.code != NE_NOERROR) { fprintf(fpout, "Error from nag_dge_norm (f16rac).\n%s\n", fail.message); exit_status = 1; goto END; } fprintf(fpout, "\nSquare root of the residual sum of squares\n"); fprintf(fpout, "%11.2e\n", rnorm); } else { fprintf(fpout, "Error from nag_dgglse (f08zac).\n%s\n", fail.message); exit_status = 1; } END: if (fpin != stdin) fclose(fpin); if (fpout != stdout) fclose(fpout); if (a) NAG_FREE(a); if (b) NAG_FREE(b); if (c) NAG_FREE(c); if (d) NAG_FREE(d); if (x) NAG_FREE(x); return exit_status; }