Click here to Skip to main content
Click here to Skip to main content

MATLAB Engine API

By , 1 Jul 2003
 

Matlab Engine API demo application

Introduction

In two past articles (Solving Engineering Problems Using MATLAB C API and Solving Engineering Problems Using MATLAB C++ Math Library), I show you how can a programmer develop an application that using MATLAB features like computing complex engineering problems. But if you are not familiar with MATLAB APIs or MATLAB C++ interface or these are hard coding techniques, this article is for you.

MATLAB Engine

MATLAB provides some API functions for controlling it. These APIs required that you installed MATLAB on your target machine. We named these APIs, MATLAB Engine API. For an alternative method, you can use MATLAB ActiveX control. For more information refer to article: A class wrapper for Matlab (C) ActiveX Control by Jonathan de Halleux.

Using MATLAB Engine

For using MATLAB engine, you must follow these steps:

  1. Add matlab.h interface file to stdafx.h or any desired interface/implementation file.
  2. Add MATLAB libraries to your project. For this reason, we need these libraries: libeng.lib, libmx.lib, libmatlb.lib, libmat.lib, libmmfile.lib.
  3. Add MatlabEng.h and MatlabEng.cpp files to your project.
  4. Declare a variable with type of CMatlabEng. (Remember to include MatlabEng.h interface file).
  5. Use member functions of CMatlabEng class, to control MATLAB and send commands to it and retrieve computed values or plotted graphs!
  6. Compile your project.

CMatlabEng

Following codes are definition of CMatlabEng class. It's very simple to use.

class CMatlabEng {
public:
    int OutputBuffer(char *p, int n);
    void OpenSingleUse(const char *startcmd, void *dcom, int *retstatus); 
    int GetVisible(bool* value); 
    int SetVisible(bool value); mxArray* GetVariable(const char* name); 
    int PutVariable(const char *name, const mxArray *mp); 
    int EvalString(const char* string);
    void Open(const char* StartCmd); int Close(); CMatlabEng();
    virtual ~CMatlabEng();
    
protected:
    Engine* pEng;
}; 

CMatlabEng in detail

Table 1 is a complete reference of member functions of CMatlabEng class.


Member Function Description
int OutputBuffer(char *p, int n); OutputBuffer defines a character buffer for EvalString to return any output that ordinarily appears on the screen.
The default behavior of EvalString is to discard any standard output caused by the command it is executing. OutputBuffer (p,n) tells any subsequent calls to EvalString to save the first n characters of output in the character buffer pointed to by p.
To turn off output buffering, use OutputBuffer(ep,NULL,0);
void OpenSingleUse (const char *startcmd, void *dcom, int *retstatus); This routine allows you to start multiple MATLAB processes for the purpose of using MATLAB as a computational engine. OpenSingleUse starts a MATLAB process, establishes a connection, and returns a unique engine identifier, or NULL if the open fails. OpenSingleUse starts a new MATLAB process each time it is called.
OpenSingleUse opens a COM channel to MATLAB. This starts the MATLAB that was registered during installation. If you did not register during installation, on the command line
you can enter the command:
matlab /regserver
OpenSingleUse allows single-use instances of a MATLAB engine server. OpenSingleUse differs from Open, which allows multiple users to use the same MATLAB engine server.
int GetVisible (bool* value); Returns status of the window for the MATLAB engine session, is visible or invisible on the Windows desktop.
int SetVisible (bool value); SetVisible makes the window for the MATLAB engine session, either visible or invisible on the Windows desktop.
You can use this function to enable or disable user interaction with the MATLAB engine session.
mxArray* GetVariable (const char* name); Reads the named mxArray from the MATLAB engine session associated with ep and returns a pointer to a newly allocated mxArray structure, or NULL if the attempt fails. GetVariable fails if the named variable does not exist.
Be careful in your code to free the mxArray created by this routine when you are finished with it.
int PutVariable (const char *name, const mxArray *mp); PutVariable writes mxArray mp to the engine ep, giving it the variable name, name. If the mxArray does not exist in the workspace, it is created. If an mxArray with the same name already exists in the workspace, the existing mxArray is replaced with the new mxArray.
int EvalString (const char* string); Evaluates the expression contained in string for the MATLAB engine session, previously started by Open.
void Open (const char* StartCmd); This routine allows you to start a MATLAB process for the purpose of using MATLAB as a computational engine.
int Close(); This routine allows you to quit a MATLAB engine session.

Sample Program

Following program is a sample that uses CMatlabEng class. Program logic is very simple.

#include "stdafx.h"
#include "MatlabEng.h"

#define message(x) printf(x"\n\n")

int main(int argc, char* argv[])
{
    CMatlabEng matlab;
    
    //open new matlab session
    message("Starting MATLAB");
    matlab.Open(NULL);

    message("Hiding MATLAB");
    matlab.SetVisible(FALSE);
    message("Press any key to continue");
    getch();

    message("Showing MATLAB");
    matlab.SetVisible(TRUE);
    message("Press any key to continue");
    getch();
    
    mxArray *T = NULL;
    double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };

    //create matrix
    T = mxCreateDoubleMatrix(1, 10, mxREAL);
    memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));
    
    //send matrix T to matlab
    message("Send matrix T to matlab");
    matlab.PutVariable("T", T);

    //Evaluate matlab command
    matlab.EvalString("D = .5.*(-9.8).*T.^2;");

    //Plot results
    message("Plot(T, D)");
    matlab.EvalString("plot(T,D);");    
    matlab.EvalString("title('Position vs. Time for a falling object');");
    matlab.EvalString("xlabel('Time (seconds)');");
    matlab.EvalString("ylabel('Position (meters)');");
    matlab.EvalString("grid;");

    //pause to see results
    message("Press any key to continue");
    getch();
    
    //destroy matrix
    mxDestroyArray(T);
    
    //show MATLAB graphics capabilities
    message("Showing MATLAB graphics capabilities");
    matlab.EvalString("z=peaks(25);");
    matlab.EvalString("surf(z);");
    matlab.EvalString("colormap(jet);");
    matlab.EvalString("knot;");

    //pause
    getch();

    //close session
    matlab.Close();

    return 0;
}
Enjoy!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

A. Riazi
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
I was born in Shiraz, a very beautiful famous city in Iran. I started programming when I was 12 years old with GWBASIC. Since now, I worked with various programming languages from Basic, Foxpro, C/C++, Visual Basic, Pascal to MATLAB and now Visual C++.
I graduated from Iran University of Science & Technology in Communication Eng., and now work as a system programmer for a telecommunication industry.
I wrote several programs and drivers for Synthesizers, Power Amplifiers, GPIB, GPS devices, Radio cards, Data Acqusition cards and so many related devices.
I'm author of several books like Learning C (primary and advanced), Learning Visual Basic, API application for VB, Teach Yourself Object Oriented Programming (OOP) and etc.
I'm winner of January, May, August 2003 and April 2005 best article of month competetion, my articles are:

You can see list of my articles, by clicking here


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Output Variable Value in C++memberLaston10 Jan '07 - 10:20 
Great! I might use this in the future for dealing with larger arrays.
 
Clement
QuestionWhere is matlab.h? [modified]memberxb2111 Dec '06 - 8:53 
I'm currently using MATLAB version 7.3.0.267(R2006b)
 
Sniff | :^)
 

-- modified at 14:58 Friday 1st December, 2006
AnswerRe: Where is matlab.h?memberifeefreenow5 Dec '06 - 16:24 
You may change matlab.h to matrix.h, and it works. Good luck!
 
Prgramming

AnswerRe: Where is matlab.h?memberlgzhang5 Mar '07 - 16:59 
In fact, neither "matlab.h" nor "matrix.h" is needed to run this demo in Matlab 7.0! Also, "libmatlb.lib" and "libmmfile.lib" should be removed.
AnswerRe: Where is matlab.h?memberTAbraizYounis6 Mar '11 - 19:03 
Plz email me if you could find the answer also
I find the following error
#include"engine.h" not found
GeneralIntergrating into existing C++ project in UNIXmemberkevinyeudoi21 Aug '06 - 7:34 
Dear Riazi,
I'm currently building a C++ project and hoping to use the MATLAB ploting function to show the results. I already loaded your code into the project folder but there seems to be a runtime error, for example, "...undefined reference to CMatlabEng::CMatlabEng()..." I think my problem is how to intergrate/compile your code with mine. In other words, I don't know how to put your code into my makefile.
Please, Riazi, if you have any suggestion or know of any way to make this work, please help.
Thank you very much.
Nik.
GeneralRe: Intergrating into existing C++ project in UNIXmemberA. Riazi22 Aug '06 - 1:15 
As I know, MATLAB Engin API only works under windows. Because the API uses Automation (ActiveX) technology.
 
Best regards,
A. Riazi

Questionhow to embed matlab figure into winform?memberdahuzia13 Jul '06 - 16:47 
can you tell me how to embed the matlab figure into winform,like list control?
i use microsoft vc#2003 and matlab r2006a.
thank you very much.

 
tom
Questioncall openCV functions from matlabmemberastrho2010 May '06 - 2:48 
Hi, I need call some functions of the Intel Library OpenCV from matlab.I'm doing a project with matlab about image processing. My project director told me that there was a direct form for call this Intel library but now it's not possible.then, I'm thinking do it by a MEX-files and need help!!!Confused | :confused:
 
How can I do it?

 
Thank you very much!!!!
Pedro Fernandez.
AnswerRe: call openCV functions from matlabmemberA. Riazi10 May '06 - 6:41 
There are two ways:
1- Writing your own MEX files.
2- Create an ActiveX control containing the OpenCV codes then using the control inside your m-files.
 
Best regards,
A. Riazi

GeneralError in compilingmemberrezaghorbani15 Apr '06 - 13:09 
Hi Mr. Riazi,
 
I want to use your program, I add the lib like that?
#pragma comment(lib, "C:\MATLAB701\extern\lib\win32\lcc\libeng.lib")
#pragma comment(lib, "C:\MATLAB701\extern\lib\win32\lcc\libmx.lib")
#pragma comment(lib, "C:\MATLAB701\extern\lib\win32\lcc\libmatlb.lib")
#pragma comment(lib, "C:\MATLAB701\extern\lib\win32\lcc\libmat.lib")
#pragma comment(lib, "C:\MATLAB701\extern\lib\win32\lcc\libmmfile.lib")
 
cause my matlab lib are in C:\MATLAB701\extern\lib\win32\lcc.
 
but I got this error while I compiled the project:
 
Compiling...
MatlabClass.cpp
c:\testmatlab\eng_demo\matlabclass.cpp(4) : fatal error C1083: Cannot open precompiled header file: 'Debug/MatlabClass.pch': No such file or directory
Error executing cl.exe.
 
MatlabClass.obj - 1 error(s), 0 warning(s)
 
Your commnets and help is highly appreciated.
Best,
Reza

AnswerRe: Error in compilingmemberA. Riazi15 Apr '06 - 21:13 
Salam
The error is because of the precompiled header file (*.pch). Try to clean your build and compile the project again.
 
Best regards,
A. Riazi

Generalsimulink to flight simmembermajsheridan12 Apr '06 - 6:07 
Hi
 
I read your article about MATLAB.
 
I, like Steven Romme, would also like to know if this can be used on a simulink model?
 
I have a simulink model of an aircraft dynamics and would like to extract variables from the simulink model using C++ and feed them into Microsoft Flight Simulator so that the aircraft within the flight sim behaves like a real aircraft.
 
Passing the data to Microsoft Flight Simulator is the easy part, however getting the variables into my C++ program is what I'm not sure about....
 
Any advice would be much appreciated.
 
Thanks, Marc
AnswerRe: simulink to flight simmemberA. Riazi12 Apr '06 - 7:54 
Hi,
I haven't worked with Simulink yet but I know that there is a solution. I think you can use Real-time workshop toolbox to link Simulink models to your VC++ apps.
 
Best regards,
A. Riazi

QuestionChanged files in Matlab 7memberurglefurze5 Apr '06 - 0:44 
I have succesfully run you demonstration program under Matlab 6.5.0, but have now been upgraded to 7.0.4 (R14 service pack 2), which casues missing header errors. In a previous message, you mentioned that matlab.h needed to be replaced with mclmcr.h for the files to run under Matlab 7. However, neither file exists in my current version. Do you know if the headers been changed yet again, and what is needed now?
 
Thanks,
 
James
AnswerRe: Changed files in Matlab 7memberlgzhang5 Mar '07 - 17:02 
In fact, neither "matlab.h" nor "matrix.h" is needed to run this demo in Matlab 7.0! Also, "libmatlb.lib" and "libmmfile.lib" should be removed.
 
Good luck.
Zhang
QuestionHow to use Simulink model in VC++memberstevenromme22 Mar '06 - 12:14 
Hi,
 
I read your article with great interest and i was wondering if this works with a simulink model as well.
 
We want to use a control system diagram designed in simulink in a stand-alone VC++ (MS studio 6 or .NET 2005)
 
This system has several inputs and outputs and a lot of parameters. What we want to do is create a VC++ program that receives the input from another module over a UDP communication and sends the output back to this module over UDP.
 
Is it possible to use this simulink model in your suggested way as .m files or .mex files work?
 
Thank in advance for your reaction!
steven.romme@gmail.com
 
Steven Romme
 
-- modified at 18:15 Wednesday 22nd March, 2006
AnswerRe: How to use Simulink model in VC++memberA. Riazi24 Mar '06 - 21:00 
Hi,
I sent an email. Sorry that I couldn't reply you soon because I'm in trip. Here is Nowrouz (New days) that are first days of Iranian year.
 
Best regards,
A. Riazi
GeneralMatlab Engine and M-filesmember++Nights18 Mar '06 - 1:21 
Hi,
 
Thanks firstly for your article and the demos, I found it quite useful!
 
The problem that I am having currently is to do with calling my own functions in matlab, for example:
 
I have made a M-file in matlab called "times_two.m" and inside:
 
function y = times_two(x)
y = 2*x;

 
and now I have got your Matlab Engine code working inside my VC++ already, HOWEVER the problems occurs when I tried doing this:
 
//assume I have all the libraries included
 
int main(int argc, char* argv[])
{
CMatlabEng matlab;
matlab.Open(NULL);
matlab.EvalString("D = 100;"); // this will work
/* the fellowing will execute BUT does not return the right value */
matlab.EvalString("D = times_two(100);");
mxArray myVal = matlab.GetVariable("D");
// now I use my own print out function
myPrintingFunction(myVal);
 
matlab.Close();
 
return 0;
}

Now you would EXPECT the print out of the result will be 200, however it will just print 100 and I have tried many values on it and finally i have track down to the line:
 
matlab.EvalString("D = times_two(100);");
 
It seems as if it does not return the value to my variable "D", is it because Matlab Engine do not support user-defined functions or M-files? I am pretty sure that the function have been executed, just that it does not return the value...
 
(I am using Matlab 7 R14 - the latest release)
 
Does anyone have a solution to this??
 
Thx in advance!!
AnswerRe: Matlab Engine and M-filesmemberA. Riazi22 Mar '06 - 3:19 
Did you put your m-file in MATLAB path?
 
Best regards,
A. Riazi

GeneralRe: Matlab Engine and M-filesmemberreinsch16 Feb '07 - 3:57 
I had the same problem. However, the matlab console has to be visible otherwise whether the output could be captured nor the result is calculated.
GeneralengOpen() in engdemo.cmembervbspkc19 Feb '06 - 8:41 
I have compiled and linked engdemo.c in MSVC++ 6.0. It gives 0 errors and 0 warnings. But when executed (please see the code below) only "Hi 1" is getting printed and it just waits. Nothing happens. engOpen(NULL) is not able to connect to MATLAB. Why this is happening.
 
printf("Hi 1\n");
if (!(ep = engOpen(NULL))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
printf("Hi 2\n");
 
Then i tried going to start->Run and typing C:\matlab7\bin\win32\matlab.exe /Automation. It opens MATLAB command window only. After that if i run the engdemo.c it works ans shows the desired result.
 
Is it not possible to start the MATLAB without doing the /Automation business.
 
Thanx in advance
 
Sunil
AnswerRe: engOpen() in engdemo.cmemberA. Riazi21 Feb '06 - 6:12 
You used MATLAB 7 but the code that I provided was for MATLAB 6.5. Maybe the interface of MATLAB changed a bit.
The engOpen() runs the MATLAB in background. You can do this manually or in application (by using ShellExecute).
 
Best regards,
A. Riazi

GeneralRe: engOpen() in engdemo.cmembervbspkc21 Feb '06 - 19:57 
Dear Sir,
 
Thank you for the reply. But it didn't solve my problem. engOpen(NULL) should run the MATLAB in backgroud, but it is not happening to me. I am using MATLAB 7 and Win2K. Please see the code below.
 
int main()
{
Engine *ep;
if (!(ep = engOpen(NULL)))
{
fprintf(stderr, "\nCan't start MATLAB engine\n");
exit(0);
}
engEvalString(ep, "edit");
engClose(ep);
 
return 0;
}
 
This code gives 0 errors and 0 warnings using MSVC++6.0. But when run it doesn't open editor. Why is this so?
 
It will be gr8 if you can let me know what mistake am i doing, and why the above code is not running.
GeneralRe: engOpen() in engdemo.cmemberA. Riazi22 Feb '06 - 3:27 
Your code is correct. As I said maybe the MATLAB interface changed a bit. You know that by using engOpen() you want to use MATLAB COM interface (Automation) to load the MATLAB IDE.
The code that I provide was for MATLAB 6.5 and you want to load MATLAB 7.
 
Best regards,
A. Riazi

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 2 Jul 2003
Article Copyright 2003 by A. Riazi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid