Previous: Vector properties, Up: Vectors


8.3.11 Example programs for vectors

This program shows how to allocate, initialize and read from a vector using the functions gsl_vector_alloc, gsl_vector_set and gsl_vector_get.

     #include <stdio.h>
     #include <gsl/gsl_vector.h>
     
     int
     main (void)
     {
       int i;
       gsl_vector * v = gsl_vector_alloc (3);
       
       for (i = 0; i < 3; i++)
         {
           gsl_vector_set (v, i, 1.23 + i);
         }
       
       for (i = 0; i < 100; i++) /* OUT OF RANGE ERROR */
         {
           printf ("v_%d = %g\n", i, gsl_vector_get (v, i));
         }
     
       gsl_vector_free (v);
       return 0;
     }

Here is the output from the program. The final loop attempts to read outside the range of the vector v, and the error is trapped by the range-checking code in gsl_vector_get.

     $ ./a.out
     v_0 = 1.23
     v_1 = 2.23
     v_2 = 3.23
     gsl: vector_source.c:12: ERROR: index out of range
     Default GSL error handler invoked.
     Aborted (core dumped)

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

     #include <stdio.h>
     #include <gsl/gsl_vector.h>
     
     int
     main (void)
     {
       int i; 
       gsl_vector * v = gsl_vector_alloc (100);
       
       for (i = 0; i < 100; i++)
         {
           gsl_vector_set (v, i, 1.23 + i);
         }
     
       {  
          FILE * f = fopen ("test.dat", "w");
          gsl_vector_fprintf (f, v, "%.5g");
          fclose (f);
       }
     
       gsl_vector_free (v);
       return 0;
     }

After running this program the file test.dat should contain the elements of v, written using the format specifier %.5g. The vector could then be read back in using the function gsl_vector_fscanf (f, v) as follows:

     #include <stdio.h>
     #include <gsl/gsl_vector.h>
     
     int
     main (void)
     {
       int i; 
       gsl_vector * v = gsl_vector_alloc (10);
     
       {  
          FILE * f = fopen ("test.dat", "r");
          gsl_vector_fscanf (f, v);
          fclose (f);
       }
     
       for (i = 0; i < 10; i++)
         {
           printf ("%g\n", gsl_vector_get(v, i));
         }
     
       gsl_vector_free (v);
       return 0;
     }