You are on page 1of 4

The best way is to use the MATLAB engine from C/C++ code.

All you have to do is to invoke the MATLAB engine from C/C++


program and then you can easily execute MATLAB commands directly from the C/C++ program.
Please take care that you will have to include additional library files of MATLAB into the project, for the same to work. You can
have a look at a working example for the same as shown here.
Sampling from normal distribution
Posted on Sunday, February 10, 2013 by Jappi Bains
Many a times we need to generate random samples or rather random numbers, which essentially follow or approximate a normal
distribution. Such random numbers find extensive applications in the fields of statistics, probability, gaming etc.
We present here a very small function written in C/C++, which will generate pseudorandom numbers following a normal
distribution having mean as zero(0) and given variance (bsq). As the code uses very basic statements, same can be easily tailored for
use in other programming languages also.
//Sampling in a normal distribution with mean 0 and variance bsq
double normalSampling (double bsq)
{
double sum=0, tempB=0,b;
b=sqrt(bsq);
int i;
for (i=1; i<=12; i++)
{
srand(time(NULL)* i + rand());
tempB=(((double)rand())/RAND_MAX);
// generate a random double number between 0 and 1
tempB=2 * b * tempB;// to generate a random no between 0 and 2b
tempB=tempB-b;//to ensure random no generated falls between -b to b
sum+=tempB; // add to the cumulative sum
}
sum=sum/2;
return sum;
}

Use Matlab from C and C Plus Plus
Posted on Saturday, January 19, 2013 by admin
As C/C++ programmers we often need to do a lot of mathematical operations or we may need to visually show plots of data as
graphs, scatter plots etc. MATLAB is a package which has been designed and developed to perform the mathematical computations
efficiently.

Execute Matlab Commands From C/C++
We bring to you a demonstration for using MATLAB from C/C++ programs. Not going into much details, we just present
to you a sample code which invokes the MATLAB engine and executes the MATLAB commands from within C++
program. Same can be easily adapted to C programs by making suitable changes.
Please note that MATLAB package needs to be installed on the same machine where you are compiling and executing the following
code. Also you may have to add the matlab library files to the C/C++ project settings (include files/Library files).
Following are the required settings:
Additional Include Directory : /MATLAB/R2008a/extern/include
Additional Link Directory : MATLAB/R2008a/extern/lib/win32/microsoft
Additional Library files : libeng.lib, libmx.lib, libmex.lib, libmat.lib
You may use a CMakeLists.Txt file as explained in our previous article How To Write CMakeLists.Txt.
All the required settings shown, here goes the sample code.

#include
/*
Define the Class for the Matlab Interface operations
*/
class IntMat
{
public:
IntMat()
{
}
~IntMat()
{
}
engine *ep; //Pointer for Matlab engine, to execute matlab commands
mxArray *X, *Y;
double * ptrToMatX;
double * ptrToMatY;
/*
Declare the public member functions for Matlab interface
*/
int matInit();
void matRefresh(/*double * ptrX, double * ptrY*/);
void matExit();
};
/***********************************************************************************
* Function Definitions
*
************************************************************************************/
int IntMat :: matInit()
{
X=NULL;
Y=NULL;
/*
* Create variables for our data
*/
X = mxCreateDoubleMatrix(1, 10, mxREAL);
Y = mxCreateDoubleMatrix(1, 10, mxREAL);
/*
* Create pointers to data, for operation in C++ environment
*/
ptrToMatX=(double *) mxGetData(X);
ptrToMatY=(double *) mxGetData(Y);
/*
* Put some initial values for display in MATLAB
* as we need to initialise them before use
* This also shows how we can manipulate data being transferred to Matlab
* in C++
*/
for (int i=0;i<10;i++)
{
ptrToMatX[i]=i;
ptrToMatY[i]=10*(10-i);
}
/*
* Start the MATLAB engine locally by executing the string
* "matlab"
*/
if (!(ep = engOpen("\0"))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
//Create corresponding Matlab environment variables and assign values to them
engPutVariable(ep, "X", X);
engPutVariable(ep, "Y", Y);
// Here we show how to execute Matlab commands from C++
//Set up a Scatter graph display with suitable titles of the graph and axes
engEvalString(ep, "scrsz = get(0,'ScreenSize');");
engEvalString(ep, "figure('Position',[scrsz(3)/2 0 (scrsz(3)/2)-100 (scrsz(4)/2)-100]);");
// In following line h denotes handle to figure
engEvalString(ep, "h = scatter(X,Y,2,'XDataSource','X','YDataSource','Y');");
engEvalString(ep, "title('Scatter plot of X,Y values');");
engEvalString(ep, "xlabel('X-Axis (m)');");
engEvalString(ep, "ylabel('Y-Axis (m)');");
return EXIT_SUCCESS;
}
void IntMat :: matRefresh()
{
//update values of X and Y matlab variables
engPutVariable(ep, "X", X);
engPutVariable(ep, "Y", Y);
//Refresh the plot now and show updated X and Y values
engEvalString(ep, "refreshdata(h,'caller');");
engEvalString(ep, "refresh(h);");
engEvalString(ep, "drawnow;");
}
void IntMat :: matExit()
{
printf("Exitting Matlab\n");
//free the memory and close the matlab engine before exitting
//free the memory
mxDestroyArray(X);
mxDestroyArray(Y);
//Close the Matlab engine before exiting
engEvalString(ep, "close;");
engClose(ep);
}
void main()
{
IntMat mat;
mat.matInit();
std::cout<<"Press any key to continue and see a change of displayed data"<<std::endl;
getch();
for (int j=0;j<10;j++)
{
mat.ptrToMatY[j]=j;
mat.ptrToMatX[j]=10*(10-j);
}
mat.matRefresh();
std::cout<<"Press any key to exit program"<<std::endl;
getch();
mat.matExit();
}
</std::endl;
</std::endl;

You might also like