9.5 Transferring data fromMatlabto the C++ domain 307
Matrix determinant and square
The following code contained in the filemuse1.cc defines a matrix in
the C++ domain, callsMatlabto compute the determinant and the matrix
square, and transfers the results back to the C++ domain:
#include <iostream>
#include "engine.h"
using namespace std;
int main()
{
const int BSZ=256;
char BuFFer[BSZ];
//--- Define a matrix in C++:
const shortN=2;
double x[N][N] ={{1.0, 2.0},
{4.0, 3.0}};
//--- Start an engine session:
Engine * oliver = engOpen("matlab12 -nojvm -nosplash");
engOutputBuffer(oliver, BuFFer, BSZ);
//--- Define a character buffer:
const int BufSIZE=256;
char buFFer[BufSIZE];
engOutputBuffer(oliver, buFFer, BufSIZE);
//--- Transfer the matrix x to matlab as xm:
mxArray * xm = mxCreateDoubleMatrix(N, N, mxREAL);
memcpy((void *)mxGetPr(xm), (void *)x, sizeof(x));
engPutVariable(oliver, "xm", xm);
//--- Evaluate and print the determinant:
engEvalString(oliver, "determinant = det(mat)");
cout << BuFFer;
//--- Retrieve the determinant:
mxArray * det = engGetVariable(oliver, "determinant");
double * orizousa = mxGetPr(det);
cout << *orizousa << endl;