// Matlab4C.cpp
#include <iostream>
#include <cmath>
#include <cstdlib>
// Matlab Engine. If you want to save the labor of inputing full directory, just add this direction to include for the project
#include "D:\\Matlab\\extern\\include\\engine.h"
// Three libraries needed for this project
#pragma comment( lib, "D:\\Matlab\\extern\\lib\\win32\\microsoft\\msvc70\\libeng.lib" )
#pragma comment( lib, "D:\\Matlab\\extern\\lib\\win32\\microsoft\\msvc70\\libmex.lib" )
#pragma comment( lib, "D:\\Matlab\\extern\\lib\\win32\\microsoft\\msvc70\\libmx.lib" )
// Just found that this is a feature not in C, but C++.
//It doesn't matter for a C compiler, just delete this line and select proper header files
using namespace std;
// Well, again, in C, use main()
int _tmain(int argc, _TCHAR* argv[])
{
// Matlab computing engine
Engine * pMatlab_Engine;
// You can add an exception handle(for C++) or an error check if the Matlab is available for calculation
// btw, my guess is that engOpen is a COM-interop as CreateInstance, so, with a server address, we can
// actually run Matlab engine on server. This is tentative, no test.
pMatlab_Engine = engOpen(NULL);
// Two matrices to play with: parInput is input; parAnswer is the calculation
mxArray *parInput, *parAnswer;
// Totally non-sense-made input array
double pInputData[9] = {4.5,-5,-1,
5.0,7.3,2.3,
0.0,2.5,-4.4};
// Convert our lovely array into matrix
// Attention! C uses the row-first rule while Matlab seems to have column-first
// Be very careful that the input might become its transpose in Matlab!!!
parInput = mxCreateDoubleMatrix(3,3, mxREAL);
// Oh... the nortorious memcpy ...
// Anyway, this is a very convenient way to set up the data we want ...
// No guarantee that this line will not destroy your memory system ...
memcpy((char *) mxGetPr(parInput), (char *)pInputData, 9*sizeof(double));
// Let's do something like in Matlab
engPutVariable(pMatlab_Engine, "data", parInput);
engEvalString(pMatlab_Engine,"ans = det(data);");
// Of course, we can use functions in C environment instead of passing these COMMANDS into Matlab
// There are quite a few function as mlfMTimes to use in C
// Ref to Matlab External manual
// Actually the result is a real number, not a matrx
// but we don't know, or the compiler doesn't know beforehand
parAnswer = engGetVariable(pMatlab_Engine,"ans");
// Passing the output back to C
// We know it's a real number, so a double pointer suffices
double *pOutput;
pOutput = mxGetPr(parAnswer);
// Output stuff
fgetc(stdin);
printf("%d",*pOutput);
// Close and return the resource.
// What if you don't have this line? you might not be able to use Matlab engine untill restart
engClose(pMatlab_Engine);
return 0;
}