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

A class wrapper for Matlab(c) ActiveX Control

By , 21 Oct 2002
 

Sample Image - matlabengine.png

Introduction

Matlab(c) is a well-known scientific software covering a wide range of engineering and mathematicals fields. It contains also a set of complete and powerfull visualization tools.

Matlab(c) contains it's own language and you can easily develop applications on it. However, sometimes you will want to run it from a C/C++ application and that's where everything get's tricky. In fact, although Matlab(c) comes with a C API, it is complicated to use: linking problems, compiler special flags and other mysterious bugs (maybe I did it all wrong).

Another solution is to use the COM interface of the ActiveX control. The sad thing about this interface is that... it's COM and you end up with dozens of lines of code... That's where the CMatlabEngine gets in the play. It hides all the COM code (getting CLSID, getting IDispatch, allocating variants, setting function arguments and many others) and enables you to focus on the main part of the job: use Matlab(c).

This article will discuss the main features the class, for further details check the Doxygen documentation that is shipped with the demo project. Note that you can also generate it by running Doxygen on MatlabEngine.h

Initializing the engine

All the initialization code is contained in the constructor of CMatlabEngine. You can check that the server has been correctly initialized by calling IsInitialized:

// Initializing COM
CoInitialize(NULL);

...
// Hooking matlab engine
CMatlabEngine mt;
if (!mt.IsInitialized())
   // could not initialize matlab engine, do something about it

Do not forget to uninitialize COM when quitting the application:

CoUninitialize();

Engine main methods

The matlab engine contains 5 main methods: Execute, PutMatrix, GetMatrix, PutString and GetString

Executing Matlab(c) code:

You can execute Matlab(c) code by calling Execute( LPCTSTR szMatlabCode ):

// this code will show the classic Matlab(c) demo
mt.Execute(_T("surf(peaks)"));
mt.Execute(_T("title('demo')"));

Sending arrays to Matlab(c)

You can send array, real or complex, in the form of vector to Matlab(c) by using PutMatrix.Note that the vector in PutMatrix have to be ordered line by lines: for a matrix M of size (mxn), M(i,j) is equivalent to M[i* n + j].

UINT nRows=10; // number of rows
UINT nCols=2;  // number of columns
vector<double> v( nRows * nCols );
// filling up v
...
// sending v to Matlab(c) with name "Mv"
mt.PutMatrix( _T("M"), v, nRows, nCols);
// M is now a matrix in the Matlab(c) workspace

Retreiving arrays from matlab

You can retreive arrays (real or complex) by calling GetMatrix( It is the dual of PutMatrix):

mt.Execute(_T("v=[1 2 3; 4 5 6]';"));
vector<double> vReal;
UINT nRows, nCols;
mt.GetMatrix(_T("v"), nRows, nCols, vReal);	

nRows and nCols now contains the dimension of the array and vReal the data.

Sending string to Matlab(c)

Piece of cake using PutString:

   mt.PutString("text", "Inserting a string named text");

Getting string from Matlab(c)

Use the method GetString:

LPTSTR szText;
// we suppose that myText is a string variable in Matlab
mt.GetString("myText",szText);
Note that szText is allocated on the heap by GetString, the memory cleaning is left to the user.

Workspace

You can modify the workspace you are working on by using SetWorkspace. By default, the workspace is "base". If you want to declare global variables, use "global" workspace.

Handling the Matlab Window state

  • Minimize the command window,
    mt.MinimizeWindow();
    
  • Maximize the command window,
    mt.MaximizeWindow();
    
  • Show, hide the command window,
    mt.Show( true /* true to make it visible, false to hide it*/);
    
  • Get the visibility state the command window,
    if(mt.IsVisivle())
        // Matlab is server is visible...
    
  • Quit the command window,
    mt.Quit();
    

Known bugs and limitations

Matlab 5.3 and earlier

Some function interface from the Matlab engine have been introduced only with the version 6.0 therefore user with version earlier than 6.0 would have faced problem with the class.

If you have a Matlab earlier than v6.0, undefine the MATLAB_VERSION_6 constant that is at the beginning of MatlabEngine.h, it will disable the following functions: IsVisible, Show, PutString, GetString

Further developments

  • Write PutCellArray and GetCellArray to write and read cell arrays.

Reference and further reading

Revision History

21-10-2002Added references
10-09-2002
  • GetString is now working! At last !
  • Fixed bugs in GetResult, GetMatrix thanks to Juan Carlos Cobas.
09-25-2002
  • GetMatrix is now working! At last !
09-23-2002
  • Added PutString method
  • Added MATLAB_VERSION_6 string for Matlab version < 6. Thanks for ZHANG Yan for finding the workaround.

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

Jonathan de Halleux
Engineer
United States United States
Member
Jonathan de Halleux is Civil Engineer in Applied Mathematics. He finished his PhD in 2004 in the rainy country of Belgium. After 2 years in the Common Language Runtime (i.e. .net), he is now working at Microsoft Research on Pex (http://research.microsoft.com/pex).

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: matlab errormemberJonathan de Halleux16 Dec '03 - 21:22 
Sir,
 
I don't understand this error message. You should not be compiling .m files using the MatlabEngine ??? Are you trying to do .mex files ?
 
ps: Please encapsulate your error message in pre tags and do a full cut-and-paste of the compilation log!
 
Jonathan de Halleux.

www.dotnetwiki.org

Generalsimple questionsmemberastridwahlin15 Dec '03 - 4:44 
Hello! I'm soo happy there is code to make it able to run Matlab from C++.
 
I'm having a camera with a C++ program. I need to do things to my camera-images and find it easiest to do it in Matlab. So I've understood that in my C++ code I could just add the MatlabEngine.h and .cpp -files (and StdAfx files) to my project, include MatlabEngine.h to my C++ code, initialize and unitialize the engine and inbetween perform whatever I like to perform, correct?
 
My problem is that if I only do CoInitialize(NULL), then Matlab doesn't get initialized, so if I add "mt=new CMatlabEngine;" then my program warns me saying that I bool to false or true, but I can run the program, just not perform anything if I would like to. What can I have missed?
[ONE HOUR LATER: I took out CoInitialize(NULL) and now I could run PutString(). So is it good enough just having "mt=new CMatlabEngine;" to initialize Matlab?]
 
I can run the demo without problems, BUT you have written "/TODO: Place code here" in int APIENTRY WinMain(..) in the MatlabEngineDemo.cpp file, and I understood that line as to write some code afterwards, and I tried it, but with no results at all. I added the three lines for PutString as you have later on. What's the meaning here? should I add code or not and what kind of code could I add?
 
Merci bcp Wink | ;)
GeneralRe: simple questionsmemberJonathan de Halleux16 Dec '03 - 21:20 
astridwahlin wrote:
[ONE HOUR LATER: I took out CoInitialize(NULL) and now I could run PutString(). So is it good enough just having "mt=new CMatlabEngine;" to initialize Matlab?]
 
This should be sufficient. You don't need to call CoInitialize(NULL) if the COM interface is already initialized. Note that are not obliged to allocated dynamically CMatlabEngine.
 

astridwahlin wrote:
"/TODO: Place code here"
 
This is generated by the MFC wizard. You should modify the code at this point but add new code in the WndProc function.
Don't bother about modifying the demo version (which is for demonstration), I advise you to create a new console application and start from scratch: create an empty console project, follow the article for that.
 
Jonathan de Halleux.

www.dotnetwiki.org

QuestionNot releasing memory?memberarnonm4 Jun '03 - 1:22 
I integrated this class into a simulator that makes many calls to the CMatlabEngine::Execute() function.
Memory usage of the program increased tremendously.
I think that this is caused by m_vResult, which gets the return value from matlab.
This variable is also used in IsVisible() and GetString().
Must it be explicitly freed before reusing (I'm not too familiar with VARIANT types)?
AnswerRe: Not releasing memory? My unvalidated solutionmemberarnonm4 Jun '03 - 2:06 
This is what I did to solve the memory leaks, but I haven't debugged this much to see if it causes any damage:
 
In MatlabEngine.h, I added a protected method:
    //! Free memory that was allocated for the result member:
    void FreeResult();
In MatlabEngine.cpp I made the following changes:
In the constructor, added:
    m_vResult.bstrVal = NULL;
 
Before every call to
m_pMtlbDispApp ->Invoke(..., &m_vResult, ...)
(there are three such calls, in Execute(), IsVisible() and GetString())
I added:
    FreeResult();
 
At the end of the file I added:
void CMatlabEngine::FreeResult()
{
    if (m_vResult.vt == VT_BSTR) {
        ::SysFreeString(m_vResult.bstrVal);
        m_vResult.bstrVal = NULL;
    }
}
 
I would be happy to hear any remarks - if there is anything else that must be checked before freeing the result, or if there is anything else to initialize.
 
Hope this helps more than it hurts,
- Arnon
GeneralRe: Not releasing memory? My unvalidated solutionmemberJonathan de Halleux4 Jun '03 - 3:20 
I'll have look.
 
Jonathan de Halleux.

GeneralBug in CMatlabEngine::ErrHandlermemberarnonm26 May '03 - 3:44 
It seems like there are two small bugs in the error handler:
1. ::_tprintf should be ::_stprintf (lines 136 and 155), otherwise, the error strings errMsg and extMess are left as garbage.
2. errDesc is used without being set (line 138).
Where can you find the description of the error message?
 
Thanks,
- Arnon
GeneralRe: Bug in CMatlabEngine::ErrHandlermemberarnonm26 May '03 - 21:14 
I made some changes to the error handler so that I could see a description of the MATLAB errors that I get. Here is my modified version of ErrHandler:
 
void CMatlabEngine::ErrHandler(HRESULT hr, EXCEPINFO excep, UINT uArgErr)
{
  // Allow converting BSTR to normal strings:
  USES_CONVERSION;
 
  if (hr == DISP_E_EXCEPTION)
  {
    TCHAR errMsg[512];
 
    ::_stprintf(errMsg, TEXT("Run-time error %d:\n\n %s"),
            excep.scode & 0x0000FFFF,  //Lower 16-bits of SCODE
             OLE2T(excep.bstrDescription));                  //Text error description
    ::MessageBox(NULL, errMsg, TEXT("MATLAB Error"),
                MB_SETFOREGROUND | MB_OK);
  }
  else
  {
    LPVOID lpMsgBuf;
    ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                    FORMAT_MESSAGE_FROM_SYSTEM |
                    FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr,
                    MAKELANGID(LANG_NEUTRAL,
                    SUBLANG_DEFAULT),(LPTSTR) &lpMsgBuf,
                    0, NULL);
    if ((hr == DISP_E_TYPEMISMATCH ) ||
        (hr == DISP_E_PARAMNOTFOUND))
    {
      TCHAR extMess[512];
      ::_stprintf(extMess, TEXT("%s Position of incorrect argument is %u.\n"), (LPCTSTR) lpMsgBuf, uArgErr);
      ::MessageBox(NULL, extMess, TEXT("COM Error"), MB_OK | MB_SETFOREGROUND);
    }
    else
    {
      ::MessageBox(NULL, (LPCTSTR)lpMsgBuf, TEXT("COM Error"),MB_OK | MB_SETFOREGROUND);
    }
    ::LocalFree(lpMsgBuf);
  }
}
 
You must also add the following line to MatlabEngine.cpp:
 
#include <atlbase.h>        // Allows converting BSTR to normal strings

GeneralGood fixmemberJonathan de Halleux26 May '03 - 22:06 
Thank you for the fix. I'll post an update of the source but it will take time to get to CP.

 
Jonathan de Halleux.

GeneralThanks!memberarnonm22 May '03 - 0:39 
Thanks for this simple and very useful class.
The beautifully formatted doxygen documentation could be used as a reference for most programmers to learn from...
 
One small issue and one question:
In the article, you recommend checking IsInitialized() after instantiating the class, but you don't do this in the demo code. OMG | :OMG:
 
And for the question:
We have a limited number of licenses at work. When you open matlab but can't get a license, you get a fatal error message box, and after you close it, matlab closes. Unfortunately, IsInitialized() returns true even when a license wasn't acquired. Is there any way to make sure that the app was really opened?

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 22 Oct 2002
Article Copyright 2002 by Jonathan de Halleux
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid