# How to write and use mex files for Matlab

## Howto use predefined mexfiles

A range of mexfiles is predefined in directory `library/mex`. Many of these mexfile process ui files (see User Infos and their use) examples of these files are in directory `library/tutorial`. Note that in order to run these files you need to let matlab know where to find them:

    >> addpath path_to_bdm/library/mex

Then, you can go to `library/tutorial` and run e.g. `arx_test_mex`.

## Howto write custom mex file

Due to special nature of the mex files, the mex file can be split in three parts:

- input conversion, where input arguments are converted to IT++ structures,
- main body of algorithm, where any C++ bdm constructions can be used,
- output conversion, where resulting IT++ structures are converted to mxArrays.

The first and the third part is achieved using prepared IT++ routines, see IT++ documentation.

Script ``./buildmex is prepared to compile and link the mexfile with bdm.

    $ ./buildmex.sh my_mex_file.cpp

on Linux, or

    $ ./buildmex.bat my_mex_file.cpp

on Windows.

Example of a mexfile:

    #include <itpp/itmex.h>
    #include <estim/arx.h>

    using namespace bdm;

    void mexFunction(int n_output, mxArray *output[], int n_input, const mxArray *input[])
    {
        // Check the number of inputs and output arguments
            if(n_output!=1) mexErrMsgTxt("Wrong number of output variables!");
            if(n_input!=2) mexErrMsgTxt("Usage: arx1d(ysize, Data)!");

        // Convert input variables to IT++ format
            int ysize = mxArray2int(input[0]);
            mat Data = mxArray2mat(input[1]);

        // ------------------ Start of routine ---------------------------
            ARX Ar;
            Ar.set_statistics(ysize, 1e-5*eye(Data.rows()) );
            Ar.bayesB(Data);
            // ------------------ End of routine -----------------------------

        // Create output vectors
            output[0] = mxCreateDoubleMatrix(1,Data.rows(), mxREAL);

        // Convert the IT++ format to Matlab format for output
            vec2mxArray(Ar.posterior().mean(), output[0]);
    }