Search code examples
cgsl

GSL: how to get LDLT decomposition in GSL


I want to get the matrix l and d of matrix Q from LDLT decomposition. The same result of scipy.linalg.ldl(),here is the code:

#include <gsl/gsl_math.h>                                                                                                                                                                                        #include <gsl/gsl_sf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_errno.h>
                                                                                                                                                                                                                 int main() {
      const int dim = 3;
      double pars[3] = { 0, 0, 0 };
      double Q[9] = {
          2,-1,0,
          -1,3,-1,
          0,-1,4
      };
      int i=0,j=0;

      // Gaussian Multivariate distribution
      gsl_matrix *L = gsl_matrix_calloc(dim, dim);
      gsl_vector *S = gsl_vector_calloc(dim);
      gsl_permutation * perm = gsl_permutation_calloc(dim);

      for(i=0;i<dim*dim;i++) L->data[i]=Q[i];

>>    gsl_linalg_ldlt_decomp(L);

      for(i=0;i<3;i++){
          for(j=0;j<3;j++){
              printf("%.4f ", L->data[i*3+j]);
          }
          printf("\n");
      }

      printf("\n S=");
      for(i=0;i<3;i++)
          printf("%.4f ", S->data[i]);
      printf("\n");
  }

my compile args is gcc ldl.c -lm -llapack -lblas -lgsl

But it returns;

ldl.c: In function ‘main’:
ldl.c:39:5: warning: implicit declaration of function ‘gsl_linalg_ldlt_decomp’; did you mean ‘gsl_linalg_PTLQ_decomp’? [-Wimplicit-function-declaration]
   39 |     gsl_linalg_ldlt_decomp(L);
      |     ^~~~~~~~~~~~~~~~~~~~~~
      |     gsl_linalg_PTLQ_decomp
/usr/bin/ld: /tmp/ccSWXMMb.o: in function `main':
ldl.c:(.text+0x170): undefined reference to `gsl_linalg_ldlt_decomp'
collect2: error: ld returned 1 exit status

WHy ? What shoud I do?


Solution

  • Perhaps the best way of compiling GSL programs via the command-line is by using the flags provided by GSL itself. They can be read via the

    gsl-config
    

    utility. In your case use it as follows (providing your shell can properly process the backquoteses):

    gcc ldl.c `gsl-config --libs`
    

    If not, use the output of gsl-config --libs directly as the command line arguments.

    Anyway, your code compiles and runs on my system without any problem.