This is gsl-ref.info, produced by makeinfo version 4.2 from
gsl-ref.texi.

INFO-DIR-SECTION Scientific software
START-INFO-DIR-ENTRY
* gsl-ref: (gsl-ref).                   GNU Scientific Library - Reference
END-INFO-DIR-ENTRY


File: gsl-ref.info,  Node: Example programs for matrices,  Prev: Matrix properties,  Up: Matrices

Example programs for matrices
-----------------------------

   The program below shows how to allocate, initialize and read from a
matrix using the functions `gsl_matrix_alloc', `gsl_matrix_set' and
`gsl_matrix_get'.

     #include <stdio.h>
     #include <gsl/gsl_matrix.h>
     
     int
     main (void)
     {
       int i, j;
       gsl_matrix * m = gsl_matrix_alloc (10, 3);
     
       for (i = 0; i < 10; i++)
         for (j = 0; j < 3; j++)
           gsl_matrix_set (m, i, j, 0.23 + 100*i + j);
     
       for (i = 0; i < 100; i++)
         for (j = 0; j < 3; j++)
           printf("m(%d,%d) = %g\n", i, j,
                  gsl_matrix_get (m, i, j));
     
       return 0;
     }

Here is the output from the program.  The final loop attempts to read
outside the range of the matrix `m', and the error is trapped by the
range-checking code in `gsl_matrix_get'.

     m(0,0) = 0.23
     m(0,1) = 1.23
     m(0,2) = 2.23
     m(1,0) = 100.23
     m(1,1) = 101.23
     m(1,2) = 102.23
     ...
     m(9,2) = 902.23
     gsl: matrix_source.c:13: ERROR: first index out of range
     IOT trap/Abort (core dumped)

The next program shows how to write a matrix to a file.

     #include <stdio.h>
     #include <gsl/gsl_matrix.h>
     
     int
     main (void)
     {
       int i, j, k = 0;
       gsl_matrix * m = gsl_matrix_alloc (100, 100);
       gsl_matrix * a = gsl_matrix_alloc (100, 100);
     
       for (i = 0; i < 100; i++)
         for (j = 0; j < 100; j++)
           gsl_matrix_set (m, i, j, 0.23 + i + j);
     
       {
          FILE * f = fopen("test.dat", "w");
          gsl_matrix_fwrite (f, m);
          fclose (f);
       }
     
       {
          FILE * f = fopen("test.dat", "r");
          gsl_matrix_fread (f, a);
          fclose (f);
       }
     
       for (i = 0; i < 100; i++)
         for (j = 0; j < 100; j++)
           {
             double mij = gsl_matrix_get(m, i, j);
             double aij = gsl_matrix_get(a, i, j);
             if (mij != aij) k++;
           }
     
       printf("differences = %d (should be zero)\n", k);
       return (k > 0);
     }

After running this program the file `test.dat' should contain the
elements of `m', written in binary format.  The matrix which is read
back in using the function `gsl_matrix_fread' should be exactly equal
to the original matrix.

   The following program demonstrates the use of vector views.  The
program computes the column-norms of a matrix.

     #include <math.h>
     #include <stdio.h>
     #include <gsl/gsl_matrix.h>
     #include <gsl/gsl_blas.h>
     
     int
     main (void)
     {
       size_t i,j;
     
       gsl_matrix *m = gsl_matrix_alloc (10, 10);
     
       for (i = 0; i < 10; i++)
         for (j = 0; j < 10; j++)
           gsl_matrix_set (m, i, j, sin (i) + cos (j));
     
       for (j = 0; j < 10; j++)
         {
           gsl_vector_view column = gsl_matrix_column (m, j);
           double d;
     
           d = gsl_blas_dnrm2 (&column.vector);
     
           printf ("matrix column %d, norm = %g\n", j, d);
         }
     
       gsl_matrix_free (m);
     }

Here is the output of the program, which can be confirmed using GNU
OCTAVE,

     $ ./a.out
     matrix column 0, norm = 4.31461
     matrix column 1, norm = 3.1205
     matrix column 2, norm = 2.19316
     matrix column 3, norm = 3.26114
     matrix column 4, norm = 2.53416
     matrix column 5, norm = 2.57281
     matrix column 6, norm = 4.20469
     matrix column 7, norm = 3.65202
     matrix column 8, norm = 2.08524
     matrix column 9, norm = 3.07313
     
     octave> m = sin(0:9)' * ones(1,10)
                    + ones(10,1) * cos(0:9);
     octave> sqrt(sum(m.^2))
     ans =
     
       4.3146  3.1205  2.1932  3.2611  2.5342  2.5728
       4.2047  3.6520  2.0852  3.0731


File: gsl-ref.info,  Node: Vector and Matrix References and Further Reading,  Prev: Matrices,  Up: Vectors and Matrices

References and Further Reading
==============================

The block, vector and matrix objects in GSL follow the `valarray' model
of C++.  A description of this model can be found in the following
reference,

     B. Stroustrup, `The C++ Programming Language' (3rd Ed), Section
     22.4 Vector Arithmetic.  Addison-Wesley 1997, ISBN 0-201-88954-4.


File: gsl-ref.info,  Node: Permutations,  Next: Combinations,  Prev: Vectors and Matrices,  Up: Top

Permutations
************

   This chapter describes functions for creating and manipulating
permutations. A permutation p is represented by an array of n integers
in the range 0 .. n-1, where each value p_i occurs once and only once.
The application of a permutation p to a vector v yields a new vector v'
where v'_i = v_{p_i}.  For example, the array (0,1,3,2) represents a
permutation which exchanges the last two elements of a four element
vector.  The corresponding identity permutation is (0,1,2,3).

   Note that the permutations produced by the linear algebra routines
correspond to the exchange of matrix columns, and so should be
considered as applying to row-vectors in the form v' = v P rather than
column-vectors, when permuting the elements of a vector.

   The functions described in this chapter are defined in the header
file `gsl_permutation.h'.

* Menu:

* The Permutation struct::
* Permutation allocation::
* Accessing permutation elements::
* Permutation properties::
* Permutation functions::
* Applying Permutations::
* Reading and writing permutations::
* Permutations in Cyclic Form::
* Permutation Examples::
* Permutation References and Further Reading::


File: gsl-ref.info,  Node: The Permutation struct,  Next: Permutation allocation,  Up: Permutations

The Permutation struct
======================

   A permutation is stored by a structure containing two components,
the size of the permutation and a pointer to the permutation array.
The elements of the permutation array are all of type `size_t'.  The
`gsl_permutation' structure looks like this,

     typedef struct
     {
       size_t size;
       size_t * data;
     } gsl_permutation;


File: gsl-ref.info,  Node: Permutation allocation,  Next: Accessing permutation elements,  Prev: The Permutation struct,  Up: Permutations

Permutation allocation
======================

 - Function: gsl_permutation * gsl_permutation_alloc (size_t N)
     This function allocates memory for a new permutation of size N.
     The permutation is not initialized and its elements are undefined.
     Use the function `gsl_permutation_calloc' if you want to create a
     permutation which is initialized to the identity. A null pointer is
     returned if insufficient memory is available to create the
     permutation.

 - Function: gsl_permutation * gsl_permutation_calloc (size_t N)
     This function allocates memory for a new permutation of size N and
     initializes it to the identity. A null pointer is returned if
     insufficient memory is available to create the permutation.

 - Function: void gsl_permutation_init (gsl_permutation * P)
     This function initializes the permutation P to the identity, i.e.
     (0,1,2,...,n-1).

 - Function: void gsl_permutation_free (gsl_permutation * P)
     This function frees all the memory used by the permutation P.

 - Function: int gsl_permutation_memcpy (gsl_permutation * DEST, const
          gsl_permutation * SRC)
     This function copies the elements of the permutation SRC into the
     permutation DEST.  The two permutations must have the same size.


File: gsl-ref.info,  Node: Accessing permutation elements,  Next: Permutation properties,  Prev: Permutation allocation,  Up: Permutations

Accessing permutation elements
==============================

   The following functions can be used to access and manipulate
permutations.

 - Function: size_t gsl_permutation_get (const gsl_permutation * P,
          const size_t I)
     This function returns the value of the I-th element of the
     permutation P.  If I lies outside the allowed range of 0 to N-1
     then the error handler is invoked and 0 is returned.

 - Function: int gsl_permutation_swap (gsl_permutation * P, const
          size_t I, const size_t J)
     This function exchanges the I-th and J-th elements of the
     permutation P.


File: gsl-ref.info,  Node: Permutation properties,  Next: Permutation functions,  Prev: Accessing permutation elements,  Up: Permutations

Permutation properties
======================

 - Function: size_t gsl_permutation_size (const gsl_permutation * P)
     This function returns the size of the permutation P.

 - Function: size_t * gsl_permutation_data (const gsl_permutation * P)
     This function returns a pointer to the array of elements in the
     permutation P.

 - Function: int gsl_permutation_valid (gsl_permutation * P)
     This function checks that the permutation P is valid.  The N
     elements should contain each of the numbers 0 .. N-1 once and only
     once.


File: gsl-ref.info,  Node: Permutation functions,  Next: Applying Permutations,  Prev: Permutation properties,  Up: Permutations

Permutation functions
=====================

 - Function: void gsl_permutation_reverse (gsl_permutation * P)
     This function reverses the elements of the permutation P.

 - Function: int gsl_permutation_inverse (gsl_permutation * INV, const
          gsl_permutation * P)
     This function computes the inverse of the permutation P, storing
     the result in INV.

 - Function: int gsl_permutation_next (gsl_permutation * P)
     This function advances the permutation P to the next permutation
     in lexicographic order and returns `GSL_SUCCESS'.  If no further
     permutations are available it returns `GSL_FAILURE' and leaves P
     unmodified.  Starting with the identity permutation and repeatedly
     applying this function will iterate through all possible
     permutations of a given order.

 - Function: int gsl_permutation_prev (gsl_permutation * P)
     This function steps backwards from the permutation P to the
     previous permutation in lexicographic order, returning
     `GSL_SUCCESS'.  If no previous permutation is available it returns
     `GSL_FAILURE' and leaves P unmodified.


File: gsl-ref.info,  Node: Applying Permutations,  Next: Reading and writing permutations,  Prev: Permutation functions,  Up: Permutations

Applying Permutations
=====================

 - Function: int gsl_permute (const size_t * P, double * DATA, size_t
          STRIDE, size_t N)
     This function applies the permutation P to the array DATA of size
     N with stride STRIDE.

 - Function: int gsl_permute_inverse (const size_t * P, double * DATA,
          size_t STRIDE, size_t N)
     This function applies the inverse of the permutation P to the
     array DATA of size N with stride STRIDE.

 - Function: int gsl_permute_vector (const gsl_permutation * P,
          gsl_vector * V)
     This function applies the permutation P to the elements of the
     vector V, considered as a row-vector acted on by a permutation
     matrix from the right, v' = v P.  The j-th column of the
     permutation matrix P is given by the p_j-th column of the identity
     matrix. The permutation P and the vector V must have the same
     length.

 - Function: int gsl_permute_vector_inverse (const gsl_permutation * P,
          gsl_vector * V)
     This function applies the inverse of the permutation P to the
     elements of the vector V, considered as a row-vector acted on by
     an inverse permutation matrix from the right, v' = v P^T.  Note
     that for permutation matrices the inverse is the same as the
     transpose.  The j-th column of the permutation matrix P is given by
     the p_j-th column of the identity matrix. The permutation P and
     the vector V must have the same length.

 - Function: int gsl_permutation_mul (gsl_permutation * P, const
          gsl_permutation * PA, const gsl_permutation * PB)
     This function combines the two permutations PA and PB into a
     single permutation P, where p = pa . pb. The permutation P is
     equivalent to applying pb first and then PA.


File: gsl-ref.info,  Node: Reading and writing permutations,  Next: Permutations in Cyclic Form,  Prev: Applying Permutations,  Up: Permutations

Reading and writing permutations
================================

   The library provides functions for reading and writing permutations
to a file as binary data or formatted text.

 - Function: int gsl_permutation_fwrite (FILE * STREAM, const
          gsl_permutation * P)
     This function writes the elements of the permutation P to the
     stream STREAM in binary format.  The function returns
     `GSL_EFAILED' if there was a problem writing to the file.  Since
     the data is written in the native binary format it may not be
     portable between different architectures.

 - Function: int gsl_permutation_fread (FILE * STREAM, gsl_permutation
          * P)
     This function reads into the permutation P from the open stream
     STREAM in binary format.  The permutation P must be preallocated
     with the correct length since the function uses the size of P to
     determine how many bytes to read.  The function returns
     `GSL_EFAILED' if there was a problem reading from the file.  The
     data is assumed to have been written in the native binary format
     on the same architecture.

 - Function: int gsl_permutation_fprintf (FILE * STREAM, const
          gsl_permutation * P, const char *FORMAT)
     This function writes the elements of the permutation P
     line-by-line to the stream STREAM using the format specifier
     FORMAT, which should be suitable for a type of SIZE_T.  On a GNU
     system the type modifier `Z' represents `size_t', so `"%Zu\n"' is
     a suitable format.  The function returns `GSL_EFAILED' if there
     was a problem writing to the file.

 - Function: int gsl_permutation_fscanf (FILE * STREAM, gsl_permutation
          * P)
     This function reads formatted data from the stream STREAM into the
     permutation P.  The permutation P must be preallocated with the
     correct length since the function uses the size of P to determine
     how many numbers to read.  The function returns `GSL_EFAILED' if
     there was a problem reading from the file.


File: gsl-ref.info,  Node: Permutations in Cyclic Form,  Next: Permutation Examples,  Prev: Reading and writing permutations,  Up: Permutations

Permutations in Cyclic Form
===========================

   A permutation can be represented in both linear and cyclic notations.
The functions described in this section can be used to convert between
the two forms.

   The linear notation is an index mapping, and has already been
described above.  The cyclic notation represents a permutation as a
series of circular rearrangements of groups of elements, or "cycles".

   Any permutation can be decomposed into a combination of cycles.  For
example, under the cycle (1 2 3), 1 is replaced by 2, 2 is replaced by 3
and 3 is replaced by 1 in a circular fashion. Cycles of different sets
of elements can be combined independently, for example (1 2 3) (4 5)
combines the cycle (1 2 3) with the cycle (4 5), which is an exchange of
elements 4 and 5.  A cycle of length one  represents an element which is
unchanged by the permutation and is referred to as a "singleton".

   The cyclic notation for a permutation is not unique, but can be
rearranged into a unique "canonical form" by a reordering of elements.
The library uses the canonical form defined in Knuth's `Art of Computer
Programming' (Vol 1, 3rd Ed, 1997) Section 1.3.3, p.178.

   The procedure for obtaining the canonical form given by Knuth is,

  1. Write all singleton cycles explicitly

  2. Within each cycle, put the smallest number first

  3. Order the cycles in decreasing order of the first number in the
     cycle.

For example, the linear representation (2 4 3 0 1) is represented as (1
4) (0 2 3) in canonical form. The permutation corresponds to an
exchange of elements 1 and 4, and rotation of elements 0, 2 and 3.

   The important property of the canonical form is that it can be
reconstructed from the contents of each cycle without the brackets. In
addition, by removing the brackets it can be considered as a linear
representation of a different permutation. In the example given above
the permutation (2 4 3 0 1) would become (1 4 0 2 3).  This mapping
between linear permutations defined by the canonical form has many
important uses in the theory of permutations.

 - Function: int gsl_permutation_linear_to_canonical (gsl_permutation *
          Q, const gsl_permutation * P)
     This function computes the canonical form of the permutation P and
     stores it in the output argument Q.

 - Function: int gsl_permutation_canonical_to_linear (gsl_permutation *
          P, const gsl_permutation * Q)
     This function converts a permutation Q in canonical form back into
     linear form storing it in the output argument P.

 - Function: size_t gsl_permutation_inversions (const gsl_permutation *
          P)
     This function counts the number of inversions in the permutation P.

 - Function: size_t gsl_permutation_linear_cycles (const
          gsl_permutation * P)
     This function counts the number of cycles in the permutation P.

 - Function: size_t gsl_permutation_canonical_cycles (const
          gsl_permutation * Q)
     This function counts the number of cycles in the permutation Q,
     where Q is given in canonical form.


File: gsl-ref.info,  Node: Permutation Examples,  Next: Permutation References and Further Reading,  Prev: Permutations in Cyclic Form,  Up: Permutations

Examples
========

   The example program below creates a random permutation by shuffling
and finds its inverse.

     #include <stdio.h>
     #include <gsl/gsl_rng.h>
     #include <gsl/gsl_randist.h>
     #include <gsl/gsl_permutation.h>
     
     int
     main (void)
     {
       const size_t N = 10;
       const gsl_rng_type * T;
       gsl_rng * r;
     
       gsl_permutation * p = gsl_permutation_alloc (N);
       gsl_permutation * q = gsl_permutation_alloc (N);
     
       gsl_rng_env_setup();
       T = gsl_rng_default;
       r = gsl_rng_alloc (T);
     
       printf("initial permutation:");
       gsl_permutation_init (p);
       gsl_permutation_fprintf (stdout, p, " %u");
       printf("\n");
     
       printf(" random permutation:");
       gsl_ran_shuffle (r, p->data, N, sizeof(size_t));
       gsl_permutation_fprintf (stdout, p, " %u");
       printf("\n");
     
       printf("inverse permutation:");
       gsl_permutation_inverse (q, p);
       gsl_permutation_fprintf (stdout, q, " %u");
       printf("\n");
     
       return 0;
     }

Here is the output from the program,

     bash$ ./a.out
     initial permutation: 0 1 2 3 4 5 6 7 8 9
      random permutation: 1 3 5 2 7 6 0 4 9 8
     inverse permutation: 6 0 3 1 7 2 5 4 9 8

The random permutation `p[i]' and its inverse `q[i]' are related
through the identity `p[q[i]] = i', which can be verified from the
output.

   The next example program steps forwards through all possible 3-rd
order permutations, starting from the identity,

     #include <stdio.h>
     #include <gsl/gsl_permutation.h>
     
     int
     main (void)
     {
       gsl_permutation * p = gsl_permutation_alloc (3);
     
       gsl_permutation_init (p);
     
       do
        {
           gsl_permutation_fprintf (stdout, p, " %u");
           printf("\n");
        }
       while (gsl_permutation_next(p) == GSL_SUCCESS);
     
       return 0;
     }

Here is the output from the program,

     bash$ ./a.out
      0 1 2
      0 2 1
      1 0 2
      1 2 0
      2 0 1
      2 1 0

All 6 permutations are generated in lexicographic order.  To reverse the
sequence, begin with the final permutation (which is the reverse of the
identity) and replace `gsl_permutation_next' with
`gsl_permutation_prev'.


File: gsl-ref.info,  Node: Permutation References and Further Reading,  Prev: Permutation Examples,  Up: Permutations

References and Further Reading
==============================

The subject of permutations is covered extensively in Knuth's `Sorting
and Searching',

     Donald E. Knuth, `The Art of Computer Programming: Sorting and
     Searching' (Vol 3, 3rd Ed, 1997), Addison-Wesley, ISBN 0201896850.

For the definition of the "canonical form" see,

     Donald E. Knuth, `The Art of Computer Programming: Fundamental
     Algorithms' (Vol 1, 3rd Ed, 1997), Addison-Wesley, ISBN 0201896850.
     Section 1.3.3, `An Unusual Correspondence', p.178-179.


File: gsl-ref.info,  Node: Combinations,  Next: Sorting,  Prev: Permutations,  Up: Top

Combinations
************

   This chapter describes functions for creating and manipulating
combinations. A combination c is represented by an array of k integers
in the range 0 .. n-1, where each value c_i is from the range 0 .. n-1
and occurs at most once.  The combination c corresponds to indices of k
elements chosen from an n element vector.  Combinations are useful for
iterating over all k-element subsets of a set.

   The functions described in this chapter are defined in the header
file `gsl_combination.h'.

* Menu:

* The Combination struct::
* Combination allocation::
* Accessing combination elements::
* Combination properties::
* Combination functions::
* Reading and writing combinations::
* Combination Examples::


File: gsl-ref.info,  Node: The Combination struct,  Next: Combination allocation,  Up: Combinations

The Combination struct
======================

   A combination is stored by a structure containing three components,
the values of n and k, and a pointer to the combination array.  The
elements of the combination array are all of type `size_t', and are
stored in increasing order.  The `gsl_combination' structure looks like
this,

     typedef struct
     {
       size_t n;
       size_t k;
       size_t *data;
     } gsl_combination;


File: gsl-ref.info,  Node: Combination allocation,  Next: Accessing combination elements,  Prev: The Combination struct,  Up: Combinations

Combination allocation
======================

 - Function: gsl_combination * gsl_combination_alloc (size_t N, size_t
          K)
     This function allocates memory for a new combination with
     parameters N, K.  The combination is not initialized and its
     elements are undefined.  Use the function `gsl_combination_calloc'
     if you want to create a combination which is initialized to the
     lexicographically first combination. A null pointer is returned if
     insufficient memory is available to create the combination.

 - Function: gsl_combination * gsl_combination_calloc (size_t N)
     This function allocates memory for a new combination with
     parameters N, K and initializes it to the lexicographically first
     combination. A null pointer is returned if insufficient memory is
     available to create the combination.

 - Function: void gsl_combination_init_first (gsl_combination * C)
     This function initializes the combination C to the
     lexicographically first combination, i.e.  (0,1,2,...,k-1).

 - Function: void gsl_combination_init_last (gsl_combination * C)
     This function initializes the combination C to the
     lexicographically last combination, i.e.  (n-k,n-k+1,...,n-1).

 - Function: void gsl_combination_free (gsl_combination * C)
     This function frees all the memory used by the combination C.


File: gsl-ref.info,  Node: Accessing combination elements,  Next: Combination properties,  Prev: Combination allocation,  Up: Combinations

Accessing combination elements
==============================

   The following function can be used to access combinations elements.

 - Function: size_t gsl_combination_get (const gsl_combination * C,
          const size_t I)
     This function returns the value of the I-th element of the
     combination C.  If I lies outside the allowed range of 0 to K-1
     then the error handler is invoked and 0 is returned.


File: gsl-ref.info,  Node: Combination properties,  Next: Combination functions,  Prev: Accessing combination elements,  Up: Combinations

Combination properties
======================

 - Function: size_t gsl_combination_n (const gsl_combination * C)
     This function returns the n parameter of the combination C.

 - Function: size_t gsl_combination_k (const gsl_combination * C)
     This function returns the k parameter of the combination C.

 - Function: size_t * gsl_combination_data (const gsl_combination * C)
     This function returns a pointer to the array of elements in the
     combination C.

 - Function: int gsl_combination_valid (gsl_combination * C)
     This function checks that the combination C is valid.  The K
     elements should contain numbers from range 0 .. N-1, each number
     at most once.  The numbers have to be in increasing order.


File: gsl-ref.info,  Node: Combination functions,  Next: Reading and writing combinations,  Prev: Combination properties,  Up: Combinations

Combination functions
=====================

 - Function: int gsl_combination_next (gsl_combination * C)
     This function advances the combination C to the next combination
     in lexicographic order and returns `GSL_SUCCESS'.  If no further
     combinations are available it returns `GSL_FAILURE' and leaves C
     unmodified.  Starting with the fisrst combination and repeatedly
     applying this function will iterate through all possible
     combinations of a given order.

 - Function: int gsl_combination_prev (gsl_combination * C)
     This function steps backwards from the combination C to the
     previous combination in lexicographic order, returning
     `GSL_SUCCESS'.  If no previous combination is available it returns
     `GSL_FAILURE' and leaves C unmodified.


File: gsl-ref.info,  Node: Reading and writing combinations,  Next: Combination Examples,  Prev: Combination functions,  Up: Combinations

Reading and writing combinations
================================

   The library provides functions for reading and writing combinations
to a file as binary data or formatted text.

 - Function: int gsl_combination_fwrite (FILE * STREAM, const
          gsl_combination * C)
     This function writes the elements of the combination C to the
     stream STREAM in binary format.  The function returns
     `GSL_EFAILED' if there was a problem writing to the file.  Since
     the data is written in the native binary format it may not be
     portable between different architectures.

 - Function: int gsl_combination_fread (FILE * STREAM, gsl_combination
          * C)
     This function reads into the combination C from the open stream
     STREAM in binary format.  The combination C must be preallocated
     with correct values of n and k since the function uses the size of
     C to determine how many bytes to read.  The function returns
     `GSL_EFAILED' if there was a problem reading from the file.  The
     data is assumed to have been written in the native binary format
     on the same architecture.

 - Function: int gsl_combination_fprintf (FILE * STREAM, const
          gsl_combination * C, const char *FORMAT)
     This function writes the elements of the combination C
     line-by-line to the stream STREAM using the format specifier
     FORMAT, which should be suitable for a type of SIZE_T.  On a GNU
     system the type modifier `Z' represents `size_t', so `"%Zu\n"' is
     a suitable format.  The function returns `GSL_EFAILED' if there
     was a problem writing to the file.

 - Function: int gsl_combination_fscanf (FILE * STREAM, gsl_combination
          * C)
     This function reads formatted data from the stream STREAM into the
     combination C.  The combination C must be preallocated with
     correct values of n and k since the function uses the size of C to
     determine how many numbers to read.  The function returns
     `GSL_EFAILED' if there was a problem reading from the file.


File: gsl-ref.info,  Node: Combination Examples,  Prev: Reading and writing combinations,  Up: Combinations

Examples
========

   The example program below prints all subsets of the set {1,2,3,4}
ordered by size.  Subsets of the same size are ordered
lexicographically.

     #include <stdio.h>
     #include <gsl/gsl_combination.h>
     
     int
     main (void)
     {
       gsl_combination * c;
       size_t i;
     
       printf("All subsets of {0,1,2,3} by size:\n") ;
       for(i = 0; i <= 4; i++)
         {
           c = gsl_combination_calloc (4, i);
           do
             {
               printf("{");
               gsl_combination_fprintf (stdout, c, " %u");
               printf(" }\n");
             }
           while (gsl_combination_next(c) == GSL_SUCCESS);
           gsl_combination_free(c);
         }
     
       return 0;
     }

Here is the output from the program,

     bash$ ./a.out
     All subsets of {0,1,2,3} by size:
     { }
     { 0 }
     { 1 }
     { 2 }
     { 3 }
     { 0 1 }
     { 0 2 }
     { 0 3 }
     { 1 2 }
     { 1 3 }
     { 2 3 }
     { 0 1 2 }
     { 0 1 3 }
     { 0 2 3 }
     { 1 2 3 }
     { 0 1 2 3 }

All 16 subsets are generated, and the subsets of each size are sorted
lexicographically.


File: gsl-ref.info,  Node: Sorting,  Next: BLAS Support,  Prev: Combinations,  Up: Top

Sorting
*******

   This chapter describes functions for sorting data, both directly and
indirectly (using an index).  All the functions use the "heapsort"
algorithm.  Heapsort is an O(N \log N) algorithm which operates
in-place.  It does not require any additional storage and provides
consistent performance.  The running time for its worst-case (ordered
data)  is not significantly longer than the average and best cases.
Note that the heapsort algorithm does not preserve the relative
ordering of equal elements -- it is an "unstable" sort.  However the
resulting order of equal elements will be consistent across different
platforms when using these functions.

* Menu:

* Sorting objects::
* Sorting vectors::
* Selecting the k-th smallest or largest elements::
* Computing the rank::
* Sorting Examples::
* Sorting References and Further Reading::


File: gsl-ref.info,  Node: Sorting objects,  Next: Sorting vectors,  Up: Sorting

Sorting objects
===============

   The following function provides a simple alternative to the standard
library function `qsort'.  It is intended for systems lacking `qsort',
not as a replacement for it.  The function `qsort' should be used
whenever possible, as it will be faster and can provide stable ordering
of equal elements.  Documentation for `qsort' is available in the `GNU
C Library Reference Manual'.

   The functions described in this section are defined in the header
file `gsl_heapsort.h'.

 - Function: void gsl_heapsort (void * ARRAY, size_t COUNT, size_t
          SIZE, gsl_comparison_fn_t COMPARE)
     This function sorts the COUNT elements of the array ARRAY, each of
     size SIZE, into ascending order using the comparison function
     COMPARE.  The type of the comparison function is defined by,

          int (*gsl_comparison_fn_t) (const void * a,
                                      const void * b)

     A comparison function should return a negative integer if the first
     argument is less than the second argument, `0' if the two arguments
     are equal and a positive integer if the first argument is greater
     than the second argument.

     For example, the following function can be used to sort doubles
     into ascending numerical order.

          int
          compare_doubles (const double * a,
                           const double * b)
          {
              if (*a > *b)
                 return 1;
              else if (*a < *b)
                 return -1;
              else
                 return 0;
          }

     The appropriate function call to perform the sort is,

          gsl_heapsort (array, count, sizeof(double),
                        compare_doubles);

     Note that unlike `qsort' the heapsort algorithm cannot be made into
     a stable sort by pointer arithmetic.  The trick of comparing
     pointers for equal elements in the comparison function does not
     work for the heapsort algorithm.  The heapsort algorithm performs
     an internal rearrangement of the data which destroys its initial
     ordering.

 - Function: int gsl_heapsort_index (size_t * p, const void * ARRAY,
          size_t COUNT, size_t SIZE, gsl_comparison_fn_t COMPARE)
     This function indirectly sorts the COUNT elements of the array
     ARRAY, each of size SIZE, into ascending order using the
     comparison function COMPARE.  The resulting permutation is stored
     in P, an array of length N.  The elements of P give the index of
     the array element which would have been stored in that position if
     the array had been sorted in place.  The first element of P gives
     the index of the least element in ARRAY, and the last element of P
     gives the index of the greatest element in ARRAY.  The array
     itself is not changed.


File: gsl-ref.info,  Node: Sorting vectors,  Next: Selecting the k-th smallest or largest elements,  Prev: Sorting objects,  Up: Sorting

Sorting vectors
===============

   The following functions will sort the elements of an array or vector,
either directly or indirectly.  They are defined for all real and
integer types using the normal suffix rules.  For example, the `float'
versions of the array functions are `gsl_sort_float' and
`gsl_sort_float_index'.  The corresponding vector functions are
`gsl_sort_vector_float' and `gsl_sort_vector_float_index'.  The
prototypes are available in the header files `gsl_sort_float.h'
`gsl_sort_vector_float.h'.  The complete set of prototypes can be
included using the header files `gsl_sort.h' and `gsl_sort_vector.h'.

   There are no functions for sorting complex arrays or vectors, since
the ordering of complex numbers is not uniquely defined.  To sort a
complex vector by magnitude compute a real vector containing the
magnitudes of the complex elements, and sort this vector indirectly.
The resulting index gives the appropriate ordering of the original
complex vector.

 - Function: void gsl_sort (double * DATA, size_t STRIDE, size_t N)
     This function sorts the N elements of the array DATA with stride
     STRIDE into ascending numerical order.

 - Function: void gsl_sort_vector (gsl_vector * V)
     This function sorts the elements of the vector V into ascending
     numerical order.

 - Function: int gsl_sort_index (size_t * P, const double * DATA,
          size_t STRIDE, size_t N)
     This function indirectly sorts the N elements of the array DATA
     with stride STRIDE into ascending order, storing the resulting
     permutation in P.  The array P must be allocated to a sufficient
     length to store the N elements of the permutation.  The elements
     of P give the index of the array element which would have been
     stored in that position if the array had been sorted in place.
     The array DATA is not changed.

 - Function: int gsl_sort_vector_index (gsl_permutation * P, const
          gsl_vector * V)
     This function indirectly sorts the elements of the vector V into
     ascending order, storing the resulting permutation in P.  The
     elements of P give the index of the vector element which would
     have been stored in that position if the vector had been sorted in
     place.  The first element of P gives the index of the least element
     in V, and the last element of P gives the index of the greatest
     element in V.  The vector V is not changed.


File: gsl-ref.info,  Node: Selecting the k-th smallest or largest elements,  Next: Computing the rank,  Prev: Sorting vectors,  Up: Sorting

Selecting the k-th smallest or largest elements
===============================================

   The functions described in this section select the k-th smallest or
largest elements of a data set of size N.  The routines use an O(kN)
direct insertion algorithm which is suited to subsets that are small
compared with the total size of the dataset. For example, the routines
are useful for selecting the 10 largest values from one million data
points, but not for selecting the largest 100,000 values.  If the
subset is a significant part of the total dataset it may be faster to
sort all the elements of the dataset directly with an O(N \log N)
algorithm and obtain the smallest or largest values that way.

 - Function: void gsl_sort_smallest (double * DEST, size_t K, const
          double * SRC, size_t STRIDE, size_t N)
     This function copies the K-th smallest elements of the array SRC,
     of size N and stride STRIDE, in ascending numerical order in DEST.
     The size of the subset K must be less than or equal to N.  The
     data SRC is not modified by this operation.

 - Function: void gsl_sort_largest (double * DEST, size_t K, const
          double * SRC, size_t STRIDE, size_t N)
     This function copies the K-th largest elements of the array SRC,
     of size N and stride STRIDE, in descending numerical order in
     DEST. The size of the subset K must be less than or equal to N.
     The data SRC is not modified by this operation.

 - Function: void gsl_sort_vector_smallest (double * DEST, size_t K,
          const gsl_vector * V)
 - Function: void gsl_sort_vector_largest (double * DEST, size_t K,
          const gsl_vector * V)
     These functions copy the K-th smallest or largest elements of the
     vector V into the array DEST. The size of the subset K must be
     less than or equal to the length of the vector V.

   The following functions find the indices of the k-th smallest or
largest elements of a dataset,

 - Function: void gsl_sort_smallest_index (size_t * P, size_t K, const
          double * SRC, size_t STRIDE, size_t N)
     This function stores the indices of the K-th smallest elements of
     the array SRC, of size N and stride STRIDE, in the array P.  The
     indices are chosen so that the corresponding data is in ascending
     numerical order.  The size of the subset K must be less than or
     equal to N. The data SRC is not modified by this operation.

 - Function: void gsl_sort_largest_index (size_t * P, size_t K, const
          double * SRC, size_t STRIDE, size_t N)
     This function stores the indices of the K-th largest elements of
     the array SRC, of size N and stride STRIDE, in the array P.  The
     indices are chosen so that the corresponding data is in descending
     numerical order.  The size of the subset K must be less than or
     equal to N. The data SRC is not modified by this operation.

 - Function: void gsl_sort_vector_smallest_index (size_t * P, size_t K,
          const gsl_vector * V)
 - Function: void gsl_sort_vector_largest_index (size_t * P, size_t K,
          const gsl_vector * V)
     These functions store the indices of K-th smallest or largest
     elements of the vector V in the array P. The size of the subset K
     must be less than or equal to the length of the vector V.


File: gsl-ref.info,  Node: Computing the rank,  Next: Sorting Examples,  Prev: Selecting the k-th smallest or largest elements,  Up: Sorting

Computing the rank
==================

   The "rank" of an element is its order in the sorted data.  The rank
is the inverse of the index permutation, P.  It can be computed using
the following algorithm,

     for (i = 0; i < p->size; i++)
     {
         size_t pi = p->data[i];
         rank->data[pi] = i;
     }

This can be computed directly from the function
`gsl_permutation_inverse(rank,p)'.

   The following function will print the rank of each element of the
vector V,

     void
     print_rank (gsl_vector * v)
     {
       size_t i;
       size_t n = v->size;
       gsl_permutation * perm = gsl_permutation_alloc(n);
       gsl_permutation * rank = gsl_permutation_alloc(n);
     
       gsl_sort_vector_index (perm, v);
       gsl_permutation_inverse (rank, perm);
     
       for (i = 0; i < n; i++)
        {
         double vi = gsl_vector_get(v, i);
         printf("element = %d, value = %g, rank = %d\n",
                 i, vi, rank->data[i]);
        }
     
       gsl_permutation_free (perm);
       gsl_permutation_free (rank);
     }


File: gsl-ref.info,  Node: Sorting Examples,  Next: Sorting References and Further Reading,  Prev: Computing the rank,  Up: Sorting

Examples
========

   The following example shows how to use the permutation P to print
the elements of the vector V in ascending order,

     gsl_sort_vector_index (p, v);
     
     for (i = 0; i < v->size; i++)
     {
         double vpi = gsl_vector_get(v, p->data[i]);
         printf("order = %d, value = %g\n", i, vpi);
     }

The next example uses the function `gsl_sort_smallest' to select the 5
smallest numbers from 100000 uniform random variates stored in an array,

     #include <gsl/gsl_rng.h>
     #include <gsl/gsl_sort_double.h>
     
     int
     main (void)
     {
       const gsl_rng_type * T;
       gsl_rng * r;
     
       int i, k = 5, N = 100000;
     
       double * x = malloc (N * sizeof(double));
       double * small = malloc (k * sizeof(double));
     
       gsl_rng_env_setup();
     
       T = gsl_rng_default;
       r = gsl_rng_alloc (T);
     
       for (i = 0; i < N; i++)
         {
           x[i] = gsl_rng_uniform(r);
         }
     
       gsl_sort_smallest (small, k, x, 1, N);
     
       printf("%d smallest values from %d\n", k, N);
     
       for (i = 0; i < k; i++)
         {
           printf ("%d: %.18f\n", i, small[i]);
         }
       return 0;
     }
   The output lists the 5 smallest values, in ascending order,

     $ ./a.out
     5 smallest values from 100000
     0: 0.000005466630682349
     1: 0.000012384494766593
     2: 0.000017581274732947
     3: 0.000025131041184068
     4: 0.000031369971111417


File: gsl-ref.info,  Node: Sorting References and Further Reading,  Prev: Sorting Examples,  Up: Sorting

References and Further Reading
==============================

The subject of sorting is covered extensively in Knuth's `Sorting and
Searching',

     Donald E. Knuth, `The Art of Computer Programming: Sorting and
     Searching' (Vol 3, 3rd Ed, 1997), Addison-Wesley, ISBN 0201896850.

The Heapsort algorithm is described in the following book,

     Robert Sedgewick, `Algorithms in C', Addison-Wesley, ISBN
     0201514257.


File: gsl-ref.info,  Node: BLAS Support,  Next: Linear Algebra,  Prev: Sorting,  Up: Top

BLAS Support
************

   The Basic Linear Algebra Subprograms (BLAS) define a set of
fundamental operations on vectors and matrices which can be used to
create optimized higher-level linear algebra functionality.

   The library provides a low-level layer which corresponds directly to
the C-language BLAS standard, referred to here as "CBLAS", and a
higher-level interface for operations on GSL vectors and matrices.
Users who are interested in simple operations on GSL vector and matrix
objects should use the high-level layer, which is declared in the file
`gsl_blas.h'.  This should satisfy the needs of most users.  Note that
GSL matrices are implemented using dense-storage so the interface only
includes the corresponding dense-storage BLAS functions.  The full BLAS
functionality for band-format and packed-format matrices is available
through the low-level CBLAS interface.

   The interface for the `gsl_cblas' layer is specified in the file
`gsl_cblas.h'.  This interface corresponds the BLAS Technical Forum's
draft standard for the C interface to legacy BLAS implementations.
Users who have access to other conforming CBLAS implementations can use
these in place of the version provided by the library.  Note that users
who have only a Fortran BLAS library can use a CBLAS conformant wrapper
to convert it into a CBLAS library.  A reference CBLAS wrapper for
legacy Fortran implementations exists as part of the draft CBLAS
standard and can be obtained from Netlib.  The complete set of CBLAS
functions is listed in an appendix (*note GSL CBLAS Library::).

   There are three levels of BLAS operations,

Level 1
     Vector operations, e.g. y = \alpha x + y

Level 2
     Matrix-vector operations, e.g. y = \alpha A x + \beta y

Level 3
     Matrix-matrix operations, e.g. C = \alpha A B + C

Each routine has a name which specifies the operation, the type of
matrices involved and their precisions.  Some of the most common
operations and their names are given below,

DOT
     scalar product, x^T y

AXPY
     vector sum, \alpha x + y

MV
     matrix-vector product, A x

SV
     matrix-vector solve, inv(A) x

MM
     matrix-matrix product, A B

SM
     matrix-matrix solve, inv(A) B

The type of matrices are,

GE
     general

GB
     general band

SY
     symmetric

SB
     symmetric band

SP
     symmetric packed

HE
     hermitian

HB
     hermitian band

HP
     hermitian packed

TR
     triangular

TB
     triangular band

TP
     triangular packed

Each operation is defined for four precisions,

S
     single real

D
     double real

C
     single complex

Z
     double complex

Thus, for example, the name SGEMM stands for "single-precision general
matrix-matrix multiply" and ZGEMM stands for "double-precision complex
matrix-matrix multiply".

* Menu:

* GSL BLAS Interface::
* BLAS Examples::
* BLAS References and Further Reading::


File: gsl-ref.info,  Node: GSL BLAS Interface,  Next: BLAS Examples,  Up: BLAS Support

GSL BLAS Interface
==================

   GSL provides dense vector and matrix objects, based on the relevant
built-in types.  The library provides an interface to the BLAS
operations which apply to these objects.  The interface to this
functionality is given in the file `gsl_blas.h'.

* Menu:

* Level 1 GSL BLAS Interface::
* Level 2 GSL BLAS Interface::
* Level 3 GSL BLAS Interface::

