How to call Matlab function in C++
In order to make more people get benefits, I decide to write this tutorial in English. This tutorial displays how to call Matlab libraries in C++ in Windows platform.
Prerequisites:
1.Windows operating system, I test my code on Windows 7 Enterprise SP1 x64 and Windows 8 Pro x64.
2.Matlab, I test my code in Matlab 2010a, and newer versions are also compatible, I think.
3.Microsoft Visual Studio, I test my code on VS 2010 ultimate and VS 2012 ultimate. Express Suites maybe work well.
Step 1:
Set Path variable in Advanced system settings-> Environment Variables: C:\Program Files\MATLAB\R2010a\bin\win64 (or the path where libeng.dll is located)
Step 2:
In project properties of Visual Studio, add Additional Include directories of C++ -> General: "C:\Program Files\MATLAB\R2010a\extern\include"
Step 3:
In project properties of Visual Studio, linker->general, Additional Library Directories: "C:\Program Files\MATLAB\R2010a\extern\lib\win64\microsoft"
In project properties of Visual Studio, linker->input, Additional Dependencies: libeng.lib libmx.lib
Step 4:
Change the Active Solution Platform to x64 or x86 which depends on your Matlab runtime version.
Demo code:
The demo code will show how to create a sparse matrix, then put it into Matlab workspace.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
namespace MATLAB
{
// you can use namespace to avoid name conflicts
#include "engine.h"
}
int main()
{
double data[4] = {5.8, 6.2, 5.9, 6.1};
size_t row[4] = {0, 2, 1, 3};
size_t col[3] = {0, 2, 4};
static MATLAB::Engine *ep = MATLAB::engOpen( "\0" );
if (!ep)
{
fprintf (stderr, "\nCan't start MATLAB engine\n" );
return -1;
}
MATLAB::mxArray* M = MATLAB::mxCreateSparse(4, 2, 4, MATLAB::mxREAL);
double * pv = ( double *)MATLAB::mxGetPr(M);
memcpy (pv, data, 4 * sizeof ( double ));
size_t * pi = ( size_t *)MATLAB::mxGetIr(M);
memcpy (pi, row, 4* sizeof ( size_t ));
size_t * pj = ( size_t *)MATLAB::mxGetJc(M);
memcpy (pj, col, 3* sizeof ( size_t ));
MATLAB::engPutVariable(ep, "M" , M);
MATLAB::mxDestroyArray(M);
MATLAB::engEvalString(ep, "M = M'" );
MATLAB::engEvalString(ep, "M = full(M)" );
MATLAB::mxArray* result;
double res[8];
if ((result = MATLAB::engGetVariable(ep, "M" )) == NULL)
{
printf ( "Oops! You didn't create a variable X.\n\n" );
}
memcpy (( void *)res, ( void *)MATLAB::mxGetPr(result), sizeof (res));
for ( int i = 0 ;i < 2 ;i ++)
{
for ( int j = 0; j < 4; j ++)
{
printf ( "%lf " ,res[j * 2 + i]);
}
printf ( "\n" );
}
MATLAB::engClose(ep);
return 0;
}
|