Use Matlab from C and C Plus Plus

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++

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"<

Using kbhit in C and C++

While programming in C/C++, many a times we need to do something till the user presses a key and then decide on the further course of action in the program based upon the key input. Such a logic or program flow can be implemented using a very simple function “kbhit()”.

We are going to explain the use of the same here in following few lines.

The funciton prototype is
int kbhit();

Thus, as we see the function accepts no argument and returns an integer value. This return type remains ‘0’ (zero) till the user does not presses a key and becomes non-zero as soon as the user presses a key.

Now, if we also want to know which key the user has pressed, we have to use the getch() function alongwith kbhit() function.

A very simple code snippet showing the use of both is shown below:-


while (!kbhit())
{
......
//do cool processing here in this loop, which has to continue happening till user presses a key
.....
}
//Now the user has pressed a key
//To know which key we do following
int ch; //it can be char ch; also as u like it
ch=getch();
//now we have the user input in the variable ch
//we can decide further course of action based upon value in ch
//like as follows
if (ch==89)
{
....
//we do something if user pressed 'Y'
// note that 89 is ASCII code for 'Y'
....
}
else
{
....
//user did not press 'Y'
//so we do something else
.....
}
....

We have shown use of if statement here, while we can use any other conditional statements like while or do..while, case etc with ch depending upon our needs.

Keep on doing cool programming, as we say programming is an “Art of playing with logic”…..