Programming and Graphics

(Kiana) #1

9.5 Transferring data fromMatlabto the C++ domain 309


/* --------
Use matlab to compute the eigenvalues
and eigenvectors of a matrix
-----------*/

#include <iostream>
#include <iomanip>
#include "engine.h"

using namespace std;

int main()
{

//--- Define a matrix in C++:

const shortN=4;//size of the data matrix

double x[N][N] ={{1.0, 2.0, 3.0, 4.0},
{-4.0,-3.0, 5.0, 6.0},
{8.0,-5.0, 5.0,-6.0},
{-0.8,-3.0,-5.0, 6.0},
};

//--- Start an engine session:

Engine * bouboulina = engOpen("matlab -nojvm -nosplash");

//--- Establish a buffer:

const int BSZ=1024;
char BuFFer[BSZ];
engOutputBuffer(bouboulina, BuFFer, BSZ);

//--- Transfer x to matlab as xm:

mxArray * xmat = mxCreateDoubleMatrix(N, N, mxREAL);
memcpy(mxGetPr(xmat), x, sizeof(x));
engPutVariable(bouboulina, "matrix", xmat);

//--- Compute the eigenvalues:

engEvalString(bouboulina, "[V,D]=eig(matrix)");

//--- Display the eigenvalues:

cout << BuFFer;

//--- Retrieve the eigenvector matrix:
Free download pdf