Integrating MATLAB in C # .NET

Introduction


In this article, I will try to fully and step by step tell you how to connect MATLAB with C # .NET and make an application with an interface using the example of building a 3D plane.

Why is this needed?


Very often, a programmer faces the task of calculating complex mathematics. MATLAB, in turn, is an excellent tool for solving, but is weak in creating a full-fledged custom application (you can use MATLAB's GUI tools, but that didn’t suit me).

Instruments


  1. Microsoft Visual Studio 2008 SP1
  2. MATLAB 2010a
  3. MATLAB Component Runtime


Step 1. Linker setup


To build MATLAB dll library for integration into C # .NET, you need to configure the linker, i.e. what environment we will collect the project. First you need to install the MCR runtime (MATLAB Component Runtime). This is a set of dll libraries for full support for the MATLAB language. The installation file can be found: ... \ MATLAB \ R2011b \ toolbox \ compiler \ deploy \ win32 \ MCRInstaller. Typical installation, click next.
To configure the linker in the command window MATLAB'a type mbuild -setup. We agree with everything and choose the environment we need, in our case it is MVS 2008 SP1. We get something similar: We get joyful . All - the linker is configured.

Please choose your compiler for building standalone MATLAB applications:

Would you like mbuild to locate installed compilers [y]/n? y

Select a compiler:
[1] Lcc-win32 C 2.4.1 in C:\PROGRA~1\MATLAB\R2010a\sys\lcc
[2] Microsoft Visual C++ 2008 SP1 in C:\Program Files\Microsoft Visual Studio 9.0

[0] None

Compiler: 2

Please verify your choices:

Compiler: Microsoft Visual C++ 2008 SP1
Location: C:\Program Files\Microsoft Visual Studio 9.0

Are these correct [y]/n? y


Done

Step 2. We write the m-function


We will write the function of constructing a 3D plane in the given boundary conditions; for greater interest, we will return the function descriptor. As you can see, the function consists of six lines of code, however, it performs all of the above steps: it takes a symbol function ( ), the initial and final values ​​of the vectors of the borders of the plane (v ), the grid step ( ) and returns the descriptor ( ). We save this code as plane.m. Important: the MATLAB compiler understands only functions, i.e., each script should start with (preferably end with ) and be a separate m-file.

function res=plane(strfunc,vx0,vx1,vy0,vy1,h)
vx=vx0:h:vx1;
vy=vy0:h:vy1;
figure(1)
res=ezsurfc(strfunc,vx,vy);
end


strfuncx0,vx1,vy0,vy1hres


functionend

Step 3. Get the dynamic library


We type in the command window MATLAB'a deploytool. Create a new .NET Assembly project MATLABplane, specify the location.

image

Next, create the planeClass class, add plane.m to it and click the build button.

image

After successful compilation, the MATLABplane.dll library of interest to us is created, it will be here: ... MATLABplane \ distrib \ MATLABplane.dll.

Step 4. Create a C # .NET Application


In MVS 2008 SP1, we create a Windows Forms application in C #.

Add links to libraries

Before using the project methods, you need to add links to the compiled MATLABplane.dll library and the MWArray.dll library, you can find it at ... \ MATLAB \ R2010a \ toolbox \ dotnetbuilder \ bin \ win32 \ v2.0. After adding it should turn out:

image

To use the libraries in the project, you need to add a namespace description:

using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using MATLABplane;

Create a form

Using the toolbar in the designer, we create the form of the future application.

image

The following blocks were used to create the form: Label, TextBox, RichBox, Button.

Writing a code

For the interaction of the programming languages ​​C # and MATLAB, the MWArray C # data type corresponding to the MATLAB type was created. MWArray is an array of arrays; it can consist of variables, scalars, vectors, matrices, strings, structures, objects, etc. To get any values ​​from MWArray you need to use type casting.
The application operation algorithm should be as follows:
  1. Getting a function in a symbolic form and values ​​from text fields
  2. Calling the plane method from the planeClass class
  3. Getting the descriptor output array (type MWNumericArray)
  4. Output descriptor array in RichBox

Below is the full code with comments:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using MATLABplane;
namespace planeApp
{
  public partial class Form1 : Form
  {
      public Form1()
      {
          InitializeComponent();
          button1.Click += new EventHandler(button1_Click);//инициализация событий
          button2.Click += new EventHandler(button2_Click);
      }
      double x0, x1, y0, y1, h; //объявление переменых
      string func, s_x0, s_x1, s_y0, s_y1, s_h;
      MWArray[] res = null; //выходной массив метода plane
      MWNumericArray descriptor = null; //массив возвращаемого параметра 
      private void button1_Click(object sender, EventArgs e)//событие
      {
          try
          {
              func = textBox1.Text; //считывание с TextBox
              s_x0 = textBox2.Text;
              s_x1 = textBox3.Text;
              s_y0 = textBox4.Text;
              s_y1 = textBox5.Text;
              s_h = textBox6.Text;
              MWCharArray mw_func = new MWCharArray(func);//преобразование строки функции в тип MWCharArray
              x0 = Convert.ToDouble(s_x0); //преобразоване string в double
              x1 = Convert.ToDouble(s_x1);
              y0 = Convert.ToDouble(s_y0);
              y1 = Convert.ToDouble(s_y1);
              h = Convert.ToDouble(s_h);
              planeClass obj_plane = new planeClass(); //экземпляр класса компонента               
              res = obj_plane.plane(1, mw_func, x0, x1, y0, y1, h);//обращение к методу plane, первый параметр - это кол-во возвращаемых аргументов
              descriptor = (MWNumericArray)res[0]; //выбор первого элемента из массива MWArray и преобразование в числовой тип MWNumericArray
              double[,] d_descriptor = (double[,])descriptor.ToArray(MWArrayComponent.Real);//преобразование массива MWNUmericArray  к масииву типа double  
              for (int i = 0; i < d_descriptor.Length; i++)//вывод массива d_descriptor в RichBox
              {
                  richTextBox1.Text += i.ToString() + '\t';
                  richTextBox1.Text += d_descriptor[i, 0].ToString("0.000") + '\n';//преобразование элеметна массива double в string
              }
          }
          catch (Exception ex)//обработка исключения 
          {
              System.Windows.Forms.MessageBox.Show(ex.Message);
          }
      }
      private void button2_Click(object sender, EventArgs e)
      {
          richTextBox1.Text = string.Empty;//очистка RichBox
          res = null;//обнуление массивов
          descriptor = null;
      }
  }
}


As you can see, type casting is actively used, according to the scheme MWArray-> MWNUmericArray-> type C #.
We compile the project and see the result:

image

Literature


  1. MATLAB. Visual C # Programming, Borland JBuilder, VBA - N.K. Smolentsev
  2. C # and the .NET platform - E. Troelsen

Also popular now: