Next: , Previous: The histogram struct, Up: Histograms


22.2 Histogram allocation

The functions for allocating memory to a histogram follow the style of malloc and free. In addition they also perform their own error checking. If there is insufficient memory available to allocate a histogram then the functions call the error handler (with an error number of GSL_ENOMEM) in addition to returning a null pointer. Thus if you use the library error handler to abort your program then it isn't necessary to check every histogram alloc.

— Function: gsl_histogram * gsl_histogram_alloc (size_t n)

This function allocates memory for a histogram with n bins, and returns a pointer to a newly created gsl_histogram struct. If insufficient memory is available a null pointer is returned and the error handler is invoked with an error code of GSL_ENOMEM. The bins and ranges are not initialized, and should be prepared using one of the range-setting functions below in order to make the histogram ready for use.

— Function: int gsl_histogram_set_ranges (gsl_histogram * h, const double range[], size_t size)

This function sets the ranges of the existing histogram h using the array range of size size. The values of the histogram bins are reset to zero. The range array should contain the desired bin limits. The ranges can be arbitrary, subject to the restriction that they are monotonically increasing.

The following example shows how to create a histogram with logarithmic bins with ranges [1,10), [10,100) and [100,1000).

          gsl_histogram * h = gsl_histogram_alloc (3);
          
          /* bin[0] covers the range 1 <= x < 10 */
          /* bin[1] covers the range 10 <= x < 100 */
          /* bin[2] covers the range 100 <= x < 1000 */
          
          double range[4] = { 1.0, 10.0, 100.0, 1000.0 };
          
          gsl_histogram_set_ranges (h, range, 4);

Note that the size of the range array should be defined to be one element bigger than the number of bins. The additional element is required for the upper value of the final bin.

— Function: int gsl_histogram_set_ranges_uniform (gsl_histogram * h, double xmin, double xmax)

This function sets the ranges of the existing histogram h to cover the range xmin to xmax uniformly. The values of the histogram bins are reset to zero. The bin ranges are shown in the table below,

          bin[0] corresponds to xmin <= x < xmin + d
          bin[1] corresponds to xmin + d <= x < xmin + 2 d
          ......
          bin[n-1] corresponds to xmin + (n-1)d <= x < xmax

where d is the bin spacing, d = (xmax-xmin)/n.

— Function: void gsl_histogram_free (gsl_histogram * h)

This function frees the histogram h and all of the memory associated with it.