Click here to Skip to main content
15,860,859 members
Articles / Desktop Programming / MFC
Article

MATLAB Engine API

Rate me:
Please Sign up or sign in to vote.
4.91/5 (48 votes)
1 Jul 20033 min read 1.1M   9.1K   93   187
Using MATLAB Engine API to control MATLAB

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


Written By
CEO Solaris Electronics LLC
United Arab Emirates United Arab Emirates
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 Acquisition 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 competition, my articles are:


You can see list of my articles, by clicking here


Comments and Discussions

 
Questionhow to make my exe work on another computer Pin
Roger.Guo11-Jul-15 18:14
Roger.Guo11-Jul-15 18:14 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey26-Feb-12 19:51
professionalManoj Kumar Choubey26-Feb-12 19:51 
Questioncircular shift in matlab Pin
manncode17-Feb-12 5:46
manncode17-Feb-12 5:46 
QuestionGetting this error after building fom VC++ 2005 Pin
stunner086-Sep-11 18:36
stunner086-Sep-11 18:36 
GeneralThanks Pin
elitehussar24-May-10 6:06
elitehussar24-May-10 6:06 
Generaldata transfer from VC++ to MATLAB versionR2009a Pin
adityapatel_200626-Feb-10 0:53
adityapatel_200626-Feb-10 0:53 
GeneralOutput Value for C++ Pin
Dabauer8223-Dec-08 1:13
Dabauer8223-Dec-08 1:13 
QuestionHow to Read the BufferOutput Pin
Dabauer828-Dec-08 10:08
Dabauer828-Dec-08 10:08 
AnswerRe: How to Read the BufferOutput Pin
Dabauer8210-Dec-08 22:27
Dabauer8210-Dec-08 22:27 
QuestionPassing a 28x5700 double matrix from a C program to Matlab engine. Pin
Stefano7121-Sep-08 1:16
Stefano7121-Sep-08 1:16 
Generalmatlab error Pin
schok10821-Aug-08 7:53
schok10821-Aug-08 7:53 
Questionhow to write code ROBUST EMBEDDING OF VISUAL WATERMARKS USING DWT-SVD Pin
kishore081015-Aug-08 22:42
kishore081015-Aug-08 22:42 
Generallibmatlb.lib and libmmfile.lib Pin
traveller10221-Oct-07 11:31
traveller10221-Oct-07 11:31 
GeneralRe: libmatlb.lib and libmmfile.lib Pin
gvallemoura20-Nov-07 1:54
gvallemoura20-Nov-07 1:54 
Questionmatlab - vc++ (please help me) Pin
Arif W.P.4-Oct-07 12:15
Arif W.P.4-Oct-07 12:15 
Generalunresolved external symbol engOpen Pin
Tom_Me8-Feb-07 3:55
Tom_Me8-Feb-07 3:55 
Dir Sir,
I use Microsoft Visual Studio.NET, Matlab 6.5. I tried to use header flie "engine.h", but I meet the below problem:

This is my code:
-----------------
#include <string.h>
#include <stdio.h>

#include "engine.h"

void main()
{
Engine* ep;
ep = engOpen(NULL); // Connect to MATLAB engine
------------------

When I build project, I have the error:

error LNK2019: unresolved external symbol engOpen referenced in function_main

I look forward to hearing from you.
Thanks you so much.
Best regards,
Generalunhandled exception Pin
mdpatterson7230-Jan-07 9:29
mdpatterson7230-Jan-07 9:29 
GeneralCMatlabEng Instance as member variable doesn't work. Pin
jower111121-Jan-07 21:53
jower111121-Jan-07 21:53 
GeneralRe: CMatlabEng Instance as member variable doesn't work. Pin
S. Fischer26-Jan-07 2:36
S. Fischer26-Jan-07 2:36 
GeneralCannot open file "libeng.lib" Pin
Jungsun Um9-Jan-07 22:14
Jungsun Um9-Jan-07 22:14 
GeneralRe: Cannot open file "libeng.lib" Pin
Abbas_Riazi10-Jan-07 4:35
professionalAbbas_Riazi10-Jan-07 4:35 
AnswerRe: Cannot open file "libeng.lib" Pin
Laston10-Jan-07 9:54
Laston10-Jan-07 9:54 
QuestionOutput Variable Value in C++ Pin
Laston9-Jan-07 14:06
Laston9-Jan-07 14:06 
AnswerRe: Output Variable Value in C++ Pin
Abbas_Riazi9-Jan-07 18:10
professionalAbbas_Riazi9-Jan-07 18:10 
GeneralRe: Output Variable Value in C++ [modified] Pin
Laston10-Jan-07 9:52
Laston10-Jan-07 9:52 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.