For simulations I need to call functions in MATLAB and retrieve results from within a omnet++ simulation. There is documentation, however, it took me a while before I got it all working. So, I ended up with a small wrapper class that allows one to evaluate MATLAB code in a running MATLAB instance.

Because MATLAB has to start up the GUI every time the simulation starts (edit: I discovered it has a flag `-nojvm -nodisplay -nodesktop`

which speeds this up), it gets quite slow and annoying, and thus I also looked at writing a wrapper for octave, a language that is largely compatible with MATLAB.
Another advantage of using octave, instead of MATLAB is that octave is a shared library that runs in the same process, so one can pass around pointers.

By flipping a switch, the code will be either MATLAB or octave based.

The source and very simple, small examples can be found in source.tgz (5 KiB, modified on 27 January 2016, MD5 0b00489725ee2afbd929429f004c2355)

Click the read more link for some more info.

To use, either define `USE_MATLAB`

or `USE`

*OCTAVE** (in the code using #define USE*

`...`

, or using the compiler with the flag `-DUSE_...`

).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ```
#include "matlab.h"
int main() {
EngineBase &e=*newEngine(); // will create a MATLAB or octave instance,
// depending on which of USE_MATLAB or USE_OCTAVE is defined
me.test(); // just do some safety checks
me.eval("addpath('m-files')");
me.defineVar("argsIn", Vx{1,2,3,4,5,6});
me.getMatrix("argsIn");
// for octave it is necessary to make ret global
me.eval("global ret; ret=sin(argsIn);");
me.getMatrix("ret");
delete &me;
return 0;
}
``` |

There are also two convenience macros defined (`MEX_FUNCTION`

and `GET_ARG`

) for mex files, which are used to call c++ from within MATLAB.
Just `#define USE_MEX`

and include `matlab.h`

, as in the example given here (which is based on this example):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ```
#define USE_MEX
#include "matlab.h"
Vx arrayProduct(double x, const Vx &y) {
Vx ret(y.size());
for (size_t i=0; i<y.size(); i++) { ret[i] = x * y[i]; }
return ret;
}
MEX_FUNCTION(arrayProduct, /*num inputs*/2, /*num outputs*/1,
GET_ARG(0, double, multiplier, mxIsDouble(_arg_), mxGetScalar,
"must be scalar");
GET_ARG(1, double *, inMatrix, mxIsDouble(_arg_) && mxGetM(_arg_)>1,
mxGetPr, "must be row vector of type double");
plhs[0]=mexToNative(arrayProduct(multiplier, toVx(prhs[1])));
);
``` |

The file `Makefile`

contains the instructions to compile the code, using `mex`

and `mkoctfile`

or with a regular compiler.
The makefile will use the correct settings depending on the `WITH_OCTAVE`

and `WITH_MATLAB`

variables in the file `MATLAB-stuff`

.

The code should compile without modification with both octave and MATLAB. The correctness is not guaranteed though.

## Add a comment