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

1..2..3 ways of integrating MATLAB with the .NET

By , 18 Nov 2003
 

Abstract

In this article, I want to describe three possible techniques of integration of the .NET Framework with MATLAB, then I'll chose one of them and create a library for accessing MATLAB functionalities. The final objective is to create a C# component that encapsulates an M-file, much like MATLAB R13 COM Builder does. The only requirement of this project is to have MATLAB installed.

Introduction

MATLAB is a powerful scientific tool for math manipulation, specifically matrix manipulations, with its own scripting language, where files are .M files. Usually it's used as a standalone program, but can be integrated in two ways using other languages like Java, C and FORTRAN. With the first usage, we declare a new function or component in a native language that extends the functionalities of MATLAB, usually to improve the execution speed; this approach uses the MEX system. The second usage, described in this article, uses MATLAB functionalities from an external program, this time a program in the .NET framework. In this schema, the Java language has a special role because, from the R12 (a.k.a. 6.0), MATLAB is Java-based (specifically for the multiplatform GUI functionalities) and you can easily use Java classes in both ways. To use MATLAB from an external program, there are three possible solutions:

  1. low level C API
  2. DDE
  3. COM

I'll describe these solutions, implement in C#, from the easiest and highest level to the most difficult and efficient. Then I'll use the C API interface, to create first a wrapping class that calls the C APIs. Finally I'll show a tool to generate a C# class that encapsulates easily, a MATLAB algorithm, stored in a m-file, and publish the functionality as an object oriented set of methods. For example, given the following m-file that uses the built-in function magic:

function y = mymagic(x)
    y = magic(x);

the idea is to create a .NET library that gives the possibility to write a component like:

class MyMagic { 
   public static Matrix mymagic(Matrix m);
}

Possible MATLAB - .NET bindings

Solution 1 - COM approach

MATLAB exposes itself as a COM Automation Server, so we can use the .NET COM Interoperability to use its functions: we can work directly using a Type Library or using only the Dispatch interface. The progid of the server is Matlab.Application.

This code creates the server and executes a command cmd:

    m = CreateObject("Matlab.Application")
    m.Execute("cmd");

All the data transfer from MATLAB and our program is done through COM data types, and matrices are represented as SAFEARRAY(double) pointers, talking in COM terms. Using the COM interoperability, we can use double arrays.

    double [,] MReal;
    double [] MImag;
    Result = Matlab.Execute("a = [ 1 2 3 ; 4 5 6 ; 7 8 9];");
    call m.GetFullMatrix("a", "base", MReal, MImag);
    call m.PutFullMatrix("b", "....)

The second parameter base is the workspace where to find the matrix variable a. According to the documentation, we have two main workspaces: base and global.

This solution is quite slow because of the COM type exchange, so it's better that we go ahead finding another way. Anyway, it is present in the article source code under the folder COMMATLib that exposes a Matrix class.

Solution 2 - DDE

The Dynamic Data Exchange is a quite old but powerful service of Windows that lets applications communicate and exchange data. It's the ancestor of the whole COM and so it's the grandfather of the whole .NET. Again, as with the COM solution, we have a client, our .NET program, and the server, the MATLAB DDE Server, that communicates.

A DDE communication is made with a Service Name, like Matlab or WinWord, about a topic of discussion, like System or Engine, and is based on the exchange of data elements called items.

The problem with the DDE exchange is the data types used to exchange information, because it uses the Windows clipboard data types. Specifically MATLAB supports:

  • Text for operation results, and matrix data exchange (gulp!);
  • Metafilepict for image transfer;
  • XLTable for MATLAB-Excel data exchange;

This time we create a DDE communication with MATLAB and evaluates expressions using the EngEvalString item; to get or set Matrix data, we use an item with the same name of the matrix.

I've created a wrapper class called DDEMatlab with the same interface as COMMatlab, but this time we can exchange pictures to, like the one returned by the plot command. Anyway, the very problem with DDE is the matrix data exchange that is all text based.

Solution 3 - C API

The direct access to the MATLAB C API is the best solution in terms of performance and features, just let use P/Invoke and some unsafe pointer operations.

The C library internally uses Unix pipes or the COM to communicate with the main MATLAB instance, but in this case the data transfer is done using blocks of raw memory instead of the SAFEARRAY. So we can use the unsafe capabilities of C# to transfer efficiently matrices from and to MATLAB, it's just necessary to remember that MATLAB stores data in column wise order.

The structure of this solution is described later, with some examples of usage.

Comparison of the solutions

I've tested the three solutions too see the performance differences between them, but it's easy to imagine the results ahead: the test was done writing and reading a matrix of 200 by 200 elements. The following table synthesizes the results:

Solution Matrix Figures? Timing Read Timing Write
DDE text Yes 902ms 360ms
DDE Opt XLTable Yes 60ms 80ms
COM SAFEARRAY(double) No 30ms 30ms
Native double* TODO 10ms 20ms

The matnet library

The matnet library encapsulates the access to the MATLAB engine using the classic P/Invoke mechanism, exposed by the class MATInvoke, and provides the following features:

  • direct access to matrices, stored with different formats (Matrix class)
  • access to MAT files to load data stored in binary format (MATFile class)
  • evaluation of expressions (Evaluate method of the EngMATAccess class)

Examples and Usage

The basic usage of the matnet library requires to create an instance of the EngMATAccess that opens the communication with a MATLAB instance, or if not present, starts it up. Then the user can create instances of the Matrix class to store its data, and send evaluation commands to MATLAB.

    using (EngMATAccess mat = new EngMATAccess())
    {
        mat.Evaluate("A = [ 1 2 3; 3 5 6]"));
        double [,] mx = null;
        mat.GetMatrix("A", ref mx);
    }

There are also two more interesting examples of usage.

Interaction with the Imaging Toolbox and Bitmaps

The mateng library gives also the possibility to interact with Bitmap as MATLAB matrices, and use the MATLAB Imaging Toolbox. The program ImageDemo in the demo source code loads an image and processes it using the imnoise function using MATLAB, in this case the problem is the startup time if there are no MATLAB instances running. Internally MATLAB stores images as byte type three dimensional matrices in column wise order, as shown in the following diagram. Maybe the integration with the Bitmap class could be put inside a matnet.imaging library.

Imaging

Access with DLL

One of the interesting features of MATLAB is the translation of M-files into DLL libraries that can be used to distribute an algorithm in a very efficient form. The matnet library can be used to access also a custom DLL library (see example code). When an M-file is translated into a DLL, a function named AA is exposed as mlfAA, with Matrix parameters. These functions can be accessed from P/Invoke, for example an M-file with the function AA compiled as AAX.dll:

    function x = AA(b)
        x = b + 2

Can be accessed with the class:

    class MyDLL
    {
        [DllImport("AAX.dll")]
        static extern IntPtr mlfAA(IntPtr a);
    
        static public Matrix mlfAA(Matrix m)
        {
            return new Matrix(mlfAA((IntPtr)m));
        }
    }

Conclusions and Future Ideas

This article introduces the matnet .NET library as a method to access MATLAB functionalities from .NET applications in a very efficient way. This solution has been compared with the other two solutions (DDE & COM) available from MATLAB. The matnet library can be used to work directly with MATLAB or to expose M-files as components, it's also possible to interact with the imaging toolbox and bitmaps.

There are some things still missing:

  • a tool, M2NET, that encapsulates automatically an M-file as a .NET component or a user custom library
  • the extraction of figure and plots as Bitmap objects
  • make it work on Linux with Mono (sorry, but I haven't MATLAB for Linux)

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

Emanuele Ruffaldi
Software Developer (Senior) Scuola Superiore S.Anna
Italy Italy
Member
Assistant Professor in Applied Mechanics working in Virtual Reality, Robotics and having fun with Programming

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   
Questionhow to read a signal from vb10 to matlab? PinmemberMember 1006644420 May '13 - 19:46 
QuestionTHNX PinmemberMember 998837614 Apr '13 - 22:29 
QuestionFor simple numeric types with DllImport? PinmemberRed Baron12 Dec '12 - 5:44 
Question5 Pinmembercimadure11 Nov '12 - 9:34 
QuestionUsing matnet library with OCTAVE? PinmemberMember 943088714 Sep '12 - 7:36 
GeneralMy vote of 5 [modified] PinmemberJohannes Hillert14 Jun '12 - 7:41 
GeneralMy vote of 5 Pinmembermanoj kumar choubey13 Feb '12 - 0:02 
QuestionI guess the library doesn't work with MATLAB 7.12.0 (R2011a) PinmemberLannyland29 Nov '11 - 8:57 
NewsRe: I guess the library doesn't work with MATLAB 7.12.0 (R2011a) PinmemberJohannes Hillert15 Jun '12 - 9:11 
QuestionHave problem when create neural network from c sharp! PinmemberMember 801865928 Oct '11 - 18:17 
GeneralMy vote of 5 PinmemberSašo Mađarić3 May '11 - 8:55 
GeneralMy vote of 1 Pinmemberabo_yehia30 Apr '11 - 18:23 
Questionaccess violation issue Pinmemberkumar dhruva26 Jan '11 - 11:00 
GeneralDB Pinmemberdevvvy29 Jul '10 - 23:57 
GeneralMatlab and VB.net Pinmemberhardikyjoshi9 Feb '10 - 23:02 
GeneralMatlab .Net Builder Pinmembercoffeemist16 Nov '09 - 2:40 
GeneralRe: Matlab .Net Builder PinmemberRoy65124 Jan '10 - 8:46 
GeneralURGENT: two dimensional matrix of mixed type? {string, int, double, datetime} [modified] Pinmemberdevvvy1 Aug '09 - 22:08 
GeneralIntegrating matlab and .net Pinmemberosgarcia29 Jul '09 - 2:15 
GeneralOne more way of integrating MATLAB with .NET Pinmembervernicht25 Jul '09 - 13:35 
GeneralMATLAB Builder NE 3.0.1 Pinmemberdevvvy9 Jul '09 - 23:54 
Questionpicture-result over DDE PinmemberFabianZ15 Oct '08 - 22:24 
QuestionHow to Invoke Windows GUI's in Matlab? PinmemberChandu1416 Oct '08 - 9:45 
QuestionFor which Matlab version? Pinmemberdkiller24 Jul '08 - 0:01 
AnswerRe: For which Matlab version? Pinmembermahj16 Sep '08 - 8:26 
AnswerRe: For which Matlab version? PinmemberJohannes Hillert15 Jun '12 - 8:27 
GeneralMatlab Engine with Matlab Runtime PinmemberOfra Golani14 Jul '08 - 2:49 
GeneralRe: Matlab Engine with Matlab Runtime Pinmembermahj16 Sep '08 - 8:19 
AnswerRe: Matlab Engine with Matlab Runtime PinmemberJohannes Hillert15 Jun '12 - 8:48 
QuestionCan I use this with any matlab plugin? PinmemberSerDai8 Apr '08 - 12:33 
Questionwhat is a .p file in matlab and how can i run it from c#.net application PinmemberMember 10548024 Feb '08 - 0:49 
GeneralRe: what is a .p file in matlab and how can i run it from c#.net application PinmemberPaul Stephen12 Feb '08 - 20:07 
GeneralRe: what is a .p file in matlab and how can i run it from c#.net application PinmemberMember 105480218 Feb '08 - 0:49 
QuestionHow can I create a dll file in matlab PinmemberEhsana22 Jun '07 - 0:37 
AnswerRe: How can I create a dll file in matlab Pinmembersmithafebinkal25 Jun '08 - 19:15 
AnswerRe: How can I create a dll file in matlab PinmemberHari Om Prakash Sharma5 Jul '11 - 22:25 
QuestionCan I open more than one matlab connection? Pinmemberdana516 Jun '07 - 22:17 
Questioncan u tell me how read the detail mat.file Pinmemberleekarl7 Apr '07 - 21:31 
GeneralUnhandled exception PinmemberAjithIsKool5 Mar '07 - 18:02 
GeneralCannot find your matrix class Pinmembergrad08204 Mar '07 - 10:55 
GeneralRe: Cannot find your matrix class Pinmemberhzsong1233 Jan '08 - 5:22 
GeneralAnother exmaple of calling MATLAB functsion within C# PinmemberWook Chang5 Dec '06 - 17:47 
GeneralRe: Another exmaple of calling MATLAB functsion within C# PinmemberSerDai8 Apr '08 - 12:43 
Questioninvoking Matlab from C# Pinmembersl_krns15 Aug '06 - 23:27 
AnswerRe: invoking Matlab from C# PinmemberMat Kramer16 Aug '06 - 7:00 
Generalconverting Format32bppArgb to Matrix PinmemberAdil Gul12 Aug '06 - 6:40 
Generalmatlab c# Pinmemberamal0213 Jun '06 - 11:11 
Questionintegrate with ASP.NET Pinmemberidha0224 May '06 - 0:08 
GeneralProblems with DLL Pinmemberc01mr20 Apr '06 - 5:38 
QuestionSpeed using matlab and EngMatLib? PinmemberMah Jin Khai12 Apr '06 - 9:48 

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 19 Nov 2003
Article Copyright 2003 by Emanuele Ruffaldi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid