Интегрируем MATLAB в С#.NET
В этой статье я постараюсь максимально полно и пошагово рассказать, как связать MATLAB с С#.NET и сделать приложение с интерфейсом на примере построения 3D-плоскости.
Зачем это нужно?
Очень часто перед программистом встает задача вычисления сложной математики. MATLAB в свою очередь является отличным средством для решения, но слаб в создании полноценного пользовательского приложения (можно воспользоваться инструментами GUI MATLAB’a, но это меня не устроило).
Инструменты
- Microsoft Visual Studio 2008 SP1
- MATLAB 2010a
- MATLAB Component Runtime
Шаг 1. Настройка линкера
Чтобы собрать dll-библиотеку MATLAB’а для интеграции в C#.NET, нужно настроить линкер, т.е. какой средой мы будем собирать проект. Для начала нужно установить среду выполнения MCR (MATLAB Component Runtime). Это набор dll-библиотек для полной поддержки языка MATLAB. Установочный файл можно найти: . \MATLAB\R2011b\toolbox\compiler\deploy\win32\MCRInstaller. Установка типовая, жмем next.
Для настройки линкера в командном окне MATLAB’а набираем mbuild -setup . Со всем соглашаемся и выбираем нужную нам среду, в нашем случае это MVS 2008 SP1. Получаем что-то похожее:
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
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 . Все — линкер настроен.
Шаг 2. Пишем m-функцию
Напишем функцию построения 3D-плоскости в заданных граничных условиях, для большего интереса вернем дескриптор функции.
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
Как видно функция состоит из шести строчек кода, однако выполняет все вышеуказанные действия: в качестве входных параметров принимает символьную функцию ( strfunc ), начальные и конечные значения векторов границ плоскости (v x0,vx1,vy0,vy1 ), шаг сетки ( h ) и возвращает дескриптор ( res ).
Сохраняем данный код как plane.m.
Важно: компилятор MATLAB’а понимает только функции т.е., каждый сценарий должен начинаться с function (желательно заканчиваться end ) и быть отдельным m-файлом.
Шаг 3. Получаем динамическую библиотеку
Набираем в командном окне MATLAB’a deploytool . Создаем новый .NET Assembly проект MATLABplane, указываем размещение.
Далее создаем класс planeClass, добавляем в него plane.m и нажимаем кнопку build

После успешной компиляции создается интересующая нас библиотека MATLABplane.dll, находиться она будет здесь: . MATLABplane\distrib\MATLABplane.dll.
Шаг 4. Создаем приложение C#.NET
В MVS 2008 SP1 создаем приложение Windows Forms на С#.
Добавляем ссылки на библиотеки
Перед использованием методов проекта, необходимо добавить ссылки на скомпилированную библиотеку MATLABplane.dll и на библиотеку MWArray.dll, найти ее можно по адресу . \MATLAB\R2010a\toolbox\dotnetbuilder\bin\win32\v2.0. После добавления должно получиться:

Для использования библиотек в проекте необходимо добавить описание пространства имен:
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using MATLABplane;
Создаем форму
С помощью панели инструментов в конструкторе создаем форму будущего приложения.

Для создания формы были использованы следующие блоки: Label, TextBox, RichBox, Button.
Пишем код
- Получение функции в символьном виде и значений с текстовых полей
- Вызов метода plane из класса planeClass
- Получение выходного массива descriptor (тип MWNumericArray)
- Вывод массива descriptor в RichBox
Как видим, активно используется приведение типов, по схеме MWArray->MWNUmericArray->тип C#.
Компилируем проект и видим результат:
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
MATLAB Compiler Runtime (MCR) for linux
This Dockerfile will configure an environment into which the MATLAB Compiler Runtime will be installed and in which stand-alone MATLAB compiled applications can be executed (such as those created with deploytool or mcc).
Respective builds including MeshLab tool are also available.
You can simply run your MCR MATLAB Standalone Application executable («your_exe») with:
Each tag points to respective latest release
| tag | tag | tag |
|---|---|---|
| latest | ||
| R2020a | R2019b | R2019a |
| tag | tag | tag |
|---|---|---|
| latest-meshlab | ||
| R2020a-meshlab | R2019b-meshlab | R2019a-meshlab |
Set up your environment
Pull (suggested method)
Build (not suggested method)
To build by your own the latest tag you can git clone this repo, then execute build.sh or run:
Compile your MCR executable as Standalone Application (MATLAB Application Compiler). Follow the MathWorks’ compiler official reference
Run your MCR executable in docker
To run a Matlab Stand-Alone executable (MSAE) you can do the following:
in a single line:
«your_exe» is your MATLAB linux compiled (MSAE) Matlab Stand-Alone executable.
SPM/Standalone
A standalone SPM is a version of SPM that has been compiled using the MATLAB Compiler so that it does not require the availability of a MATLAB licence (you might want to check first here whether you have access to a MATLAB campus license).
A standalone version of SPM12 is available for download from the SPM website (select «SPM Standalone» for «SPM Version»). Please contact fil.spm@ucl.ac.uk if you need assistance.
Installation [ edit | edit source ]
Following your request, you will be given instructions to download the following components:
- The MATLAB Runtime: it contains a set of libraries that enables the execution of compiled MATLAB applications. You need to install the one that corresponds to your platform (Windows, Linux or macOS) and to the version that was used to compile SPM. The default SPM standalone requires the MATLAB Compiler Runtime (MCR) 7.13 of MATLAB R2010a available from the MCR folder from the link you will have been given. Otherwise more recent MATLAB Runtimes are downloadable from here.
- The SPM Standalone itself containing the compiled SPM, as a ZIP file.
Installation of the MATLAB Runtime [ edit | edit source ]
You need to do this operation only once, even if you use several versions of standalone SPM.
Run the MCRInstaller executable you downloaded and follow the instructions.
Windows installation requires to have administrative privileges and you might also have to install the Visual C++ Redistributable Package (vcredist_*.exe), that can be found in the same folder as the MCRInstaller. We also recommend you restart Windows at this point.
If you run into problems, or want to learn more, see:
To install the MCR on Linux from the command line, type:
Installation of the SPM Standalone [ edit | edit source ]
- Unzip the spm12_rxxx.zip archive containing the SPM Standalone in an appropriate folder. It contains a number of small executables for each supported platform and a large spm12.ctf file containing the compiled version of SPM12 itself.
- The first time the standalone application will be executed, the CTF file will be unpacked in a subfolder so if you installed the CTF in a folder that requires administrative permission for write access, you should execute the application once under those privileges — see below.
- On Mac, you also need to unzip the spm12_maci64.zip archive.
Usage [ edit | edit source ]
To start SPM graphical user interface:
- on Windows: double-click on spm12_wxx.exe
- on Linux, type
where the argument is the path to your MCR installation.
- on Mac, type
where the argument is the path to your MCR installation.
The first execution should take longer to start as the CTF file will be unpacked. When installing SPM system-wide, you should do the first unpacker execution as root, i.e.
On Linux/Mac, you can edit the Shell script run_spm12.sh to hardcode the location of the MCR installation, thus removing the need of providing it on the command line.
The other arguments that can be used are the modality (as in `spm fmri`) or the keyword `batch` to start directly the batch system window, e.g.:
Furthermore, `batch` followed by a batch filename (*.mat or *.m) will start SPM, execute the batch and quit:
Trouble-shooting [ edit | edit source ]
- Why do I receive an error regarding missing mclmcrrt7x.dll ?
The first thing to try is restarting your computer, if you haven’t already, since Windows can fail to find this dll even when the path is correctly set if it hasn’t been restarted. If you still have problems, see: http://www.mathworks.com/support/solutions/en/data/1-1IW46N/
- What to do if I get the error «Unable to obtain exclusive lock on CTF directory because of a file access error.«?
You need to set variable MCR_INHIBIT_CTF_LOCK to 1, see this.
- What to do if I get the error «readlink: illegal option — f» on a Mac?
Change the last line of run_spm12.sh so that it reads:
- How to have the standalone version using a single computational thread?
All recent versions of the standalone SPM are compiled with the «-R -singleCompThread» flag in mcc so that they will use a single thread at runtime.
Previous version r4290, was not using this compilation option so you might want to have your MATLAB script to start with maxNumCompThreads(1); to have the same effect.
- Why do I get a warning «Process manager already initialized — can’t fully enable headless mode.» followed by a crash on Mac OS?
Try installing XQuartz (you must logout and back in again after installing XQuartz).
- What to do if I get the error «Error: libXp.so.6: cannot open shared object file: No such file or directory«?
You need to install the package containing libXp on your Linux platform:
If you don’t find this package on Ubuntu, try installing libXp manually (compilation might require to install packages autoconf autogen xutils-dev and x11proto-print-dev):
Alternatively you can find packages for Ubuntu or Debian that can be installed after download with dpkg -i libxp6_1.0.2-2_amd64.deb.
- What to do if I get the error «This process is attempting to exclude an item from Time Machine by path without administrator privileges. This is not supported.«?
Run the standalone as root once, i.e. start the command line with sudo.
- Why do I get an error «Library not loaded: /usr/X11/lib/libXext.6.dylib» on Mac?
Have a look at [1], you probably have to reinstall XQuartz.
- Why does standalone SPM crash when starting the GUI?
This is discussed here and can be fixed by adding the following in run_spm12.sh:
Frequently Asked Questions [ edit | edit source ]
- Will it run faster?
- Is it possible to add other SPM toolboxes?
No: only core SPM toolboxes are available, contributed SPM toolboxes are not present and cannot be added without a whole recompilation.
- How to compile the SPM standalone by myself?
Have a look at config/spm_make_standalone.m and spm_standalone.m in your SPM installation.
Open MATLAB, at the command line, addpath the SPM directory (if not done already), run spm_jobman(‘initcfg’), then run spm_make_standalone. The compilation process takes several minutes. By default, the newly compiled standalone SPM will be saved in a standalone directory.
- How to create a shortcut on your Desktop for a faster launch?
On Linux, for achieving menu entries, you can install an appropriate .desktop file and an icon file for SPM. For example, save the following as spm12.desktop (modify according to your needs/MCR version):
MathWorks MATLAB
Есть несколько вариантов запуска MATLAB-программ с использованием кластера:
при условии, что в текущей директории есть файл myfunc.m , в котором определена функция myfunc . В этом случае число одновременно запущенных расчетов ограничено числом имеющихся у нас лицензий. Можно запустить одновременно пять расчетов.
Пожалуй, самый простой способ, это способ, не требующий компиляции, т.е. способ № 1. О нём подробнее рассказано в следующем разделе.
Запуск MATLAB-программ в пакетном режиме
MATLAB Compiler
Команда выведет на экран:
Нужно ввести '1' и нажать кнопку Enter.
Запустите на узле MATLAB GUI , переключите вверху на закладку 'APPS' и нажмите на стрелочку справа от строки с иконками: 
или, если дистрибутив скачан с сайта:
Parallel Computing Toolbox
Технология, позволяющая распараллеливать выполнение программ на несколько процессорных ядер, а также использовать NVidia GPU.
Distributed Computing Server
Предоставляет возможность запуска программ MATLAB (в том числе, распараллеливающихся на несколько вычислительных узлов) на кластере, через разные планировщики, включая PBS Pro. Является развитием 'Parallel Computing Toolbox'. Пользователь работает через стандартный графический интерфейс MATLAB (далее называемый 'клиент') и через него получает дополнительные вычислительные ресурсы на кластере. На нашем комплексе возможны два варианта использования, настраиваемые разными способами:
Настройка клиента на кластере
Настройка клиента на ПК
Вместо '/mnt/storage/home/hpcuser/matlab' укажите путь до директории для временных файлов на кластере — или в своей домашней директории, или в своей рабочей области.
Вместо '/mnt/storage/home/hpcuser/matlab' укажите путь до директории для временных файлов на кластере — или в своей домашней директории, или в своей рабочей области.