/* nag_make_indices (m01zac) Example Program. * * Copyright 1990 Numerical Algorithms Group. * * Mark 2 revised, 1992. * Mark 5 revised, 1998. * Mark 7 revised, 2001. * Mark 8 revised, 2004. * */ #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b) { double x = *((const double *) a); double y = *((const double *) b); return(x < y?-1:(x == y?0:1)); } #ifdef __cplusplus } #endif #define VEC(I, J) vec[(I) *tdvec + J] int main(int argc, char *argv[]) { FILE *fpin, *fpout; Integer exit_status = 0, tdvec; NagError fail; double *vec = 0; size_t i, j, m, n, *rank = 0; INIT_FAIL(fail); /* Check for command-line IO options */ fpin = nag_example_file_io(argc, argv, "-data", NULL); fpout = nag_example_file_io(argc, argv, "-results", NULL); /* Skip heading in data file */ fscanf(fpin, "%*[^\n]"); fprintf(fpout, "nag_make_indices (m01zac) Example Program Results\n"); fscanf(fpin, "%" NAG_UFMT "%" NAG_UFMT "", &m, &n); if (m >= 1 && n >= 1 && n <= n) { if (!(vec = NAG_ALLOC(m*n, double)) || !(rank = NAG_ALLOC(m, size_t))) { fprintf(fpout, "Allocation failure\n"); exit_status = -1; goto END; } tdvec = n; } else { fprintf(fpout, "Invalid m or n.\n"); exit_status = 1; return exit_status; } for (i = 0; i < m; ++i) for (j = 0; j < n; ++j) fscanf(fpin, "%lf", &VEC(i, j)); /* nag_rank_sort (m01dsc). * Rank sort of set of values of arbitrary data type */ nag_rank_sort((Pointer) vec, m, (ptrdiff_t)(n*sizeof(double)), compare, Nag_Ascending, rank, &fail); if (fail.code != NE_NOERROR) { fprintf(fpout, "Error from nag_rank_sort (m01dsc).\n%s\n", fail.message); exit_status = 1; goto END; } /* nag_make_indices (m01zac). * Inverts a permutation converting a rank vector to an * index vector or vice versa */ nag_make_indices(rank, m, &fail); if (fail.code != NE_NOERROR) { fprintf(fpout, "Error from nag_make_indices (m01zac).\n%s\n", fail.message); exit_status = 1; goto END; } fprintf(fpout, "Matrix with rows sorted according to column 1\n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) fprintf(fpout, " %7.1f ", VEC(rank[i], j)); fprintf(fpout, "\n"); } END: if (fpin != stdin) fclose(fpin); if (fpout != stdout) fclose(fpout); if (vec) NAG_FREE(vec); if (rank) NAG_FREE(rank); return exit_status; }