Using dpp to Do Matrix Algebra in D

This post shows how to do matrix algebra in D by using dpp to call into the Gretl library. Gretl is a GUI program for econometric and statistical analysis written in C. The authors also make the underlying C API available, and due to its extensive functionality and convenient (by C standards) interface, it is quite popular.

The example involves creating, transposing, and multiplying matrices on Ubuntu 16.04. Other flavors of Linux may require modifications of the commands.

Install Gretl

sudo apt-get install libgretl1-dev

Install libclang

sudo apt-get install libclang1-3.9 libclang-3.9-dev
dub fetch libclang
dub build libclang

Install dpp

dub fetch dpp
dub build dpp

You probably want to create a symlink from the d++ binary to a directory in your path, but I will write out the full path below, so as to avoid getting sidetracked.

Write a program calling Gretl functions

Put the code below into a file called matrix-example.dpp. All of these functions can be found in the gretl_matrix.h and gretl_matrix.c source files.

#include "libgretl.h"
import std.utf;

void main() {
    gretl_matrix * m = gretl_matrix_alloc(3,2);
    
    m.val[0..6] = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6];
    gretl_matrix_print(m, "Original matrix".toUTFz!(const(char)*));
    
    gretl_matrix * mt = gretl_matrix_alloc(2,3);
    gretl_matrix_transpose(mt, m);
    gretl_matrix_print(mt, "Transpose of the original matrix".toUTFz!(const(char)*));
    
    gretl_matrix * mm = gretl_matrix_alloc(3,3);
    gretl_matrix_multiply(m, mt, mm);
    gretl_matrix_print(mm, "Product of the original matrix and its transpose".toUTFz!(const(char)*));
    
    gretl_matrix_free(mm);
    gretl_matrix_free(mt);
    gretl_matrix_free(m);
}

Compile and run

~/.dub/packages/dpp-0.0.2/dpp/bin/d++ matrix_example.dpp \
    -L/usr/local/lib/libgretl-1.0.so \
  --include-path=/usr/include/glib-2.0 \
  --include-path=/usr/lib/x86_64-linux-gnu/glib-2.0/include \
  --include-path=/usr/local/include/gretl/
./matrix_example

Index    Home