C# application program and MATLAB joint programming

This article mainly combines the convenience and power of C# to write applications and the wide application of MATLAB in the industrial science community. Combining the advantages of the two, the windows desktop application written in C# is used as UI interaction to receive user configuration, and automatically according to the user's operation on the front-end application interface. Control the operation of MATLAB and return the results of MATLAB calculations to the desktop application for display.

1 C# introduction and learning

C# is very convenient for writing desktop applications of windows system. Visual studio has provided a very user-friendly design interface and interaction. The learning speed is fast and the learning cost is very low. MATLAB is widely used in numerical calculation, system simulation and control. However, the design provided by MATLAB itself has fewer GUI functions, and the controls are very simple, all based on the form of callback for UI interaction. For simple MATLAB programs, you can directly use the GUI provided by MATLAB for design.
C# learning can refer to books:

  1. C# development actual combat 1200 cases
  2. C# Getting Started Classic Sixth Edition
  3. Tomorrow's technology C# development entry and project actual combat

C# can develop a series of Microsoft applications such as desktop applications, Web, mobile apps, and tablets. C# is an object-oriented programming language. For the basics of learning C, the syntax of variable definitions, If, For, and while are exactly the same. For the basics of learning process-oriented Python or Java, the definitions of classes are basically similar, and there are A large number of system libraries can be called, and the learning cost is very low.
C# is mainly used for windows development applications divided into the following three types:

Types of Features advantage Disadvantage
Console automation Cross-platform, automation, fast Command line mode, no UI interaction
WinForm windows native UI Quick to get started, many documents are widely used CPU-bound、hard to scale
WPF Rich UI design Program and interface design are completely independent Need to write XAML, too much configuration

Among them, CPU-bound means that only the CPU can be used, and the GPU cannot be used for display and calculation. Hard to scale refers to screens that are difficult to adapt to multiple sizes and resolutions, and scaling is prone to distortion or problems.

2 Introduction to MATLAB

Presumably, the students who clicked on this blog no longer need MATLAB introduction. Of course, one point needs to be explained: MATLAB can automatically control the operation of Simulink, automatic modeling and other methods of use through the m language. And C# can control MATLAB to run various commands, functions, scripts, etc., so in principle, C# can control MATLAB to complete all its functions.

3 C# application and MATLAB mixed programming

There are mainly the following two ways to implement C# calling MATLAB. The first way is that C# functions call a dynamic link library (dll) compiled by the built-in or user-defined functions in MATLAB. As shown in the figure below, the custom function gets the dll file through the compiler, and then C# calls the dll file to implement the function call.
Insert picture description here
As shown in the figure above, this method can run independently without relying on MATLAB. However, it can only call some MATLAB functions. For example, Simulink simulation cannot be completed, and the functions are limited.
The second method is that the C# function uses the COM automatic control interface to directly control the variables, run commands or functions in the MATLAB workspace, and take out MATLAB to return the result of the operation, as shown in the following figure.
Insert picture description here
The C# application directly controls the operation of MATLAB, which can theoretically realize all the functions of MATLAB. However, the first time you need to start MATLAB Server (equivalent to opening MATLAB once), it takes a long time.
COM is the abbreviation of Component Object Module. It is a universal object interface. Any language can implement calling it as long as it conforms to this interface standard. MATLAB makes the key running programs under it into COM components for other languages ​​to call. C#, C++, VB, Excel, etc. can automatically call MATLAB based on COM and control the operation of MATLAB.
MATLAB provides a lot of calling functions based on COM, which can complete many basic routine running commands of MATLAB. The figure below shows the COM interface functions that MATLAB can use as a server.
You can see in the MATLAB help file: Call COM Objects; MATLAB API for Other Languages; MATLAB API for COM Automation Server
Insert picture description here
As can be seen in the above figure, Execute is the most important function, which is used to execute MATLAB command. According to the execution function or command line, scripts are used to automatically control tasks such as Simulink modeling and operation. At the same time, COM automation is widely used in windows software, such as C# application program to automatically control word, excel and other software to realize automatic reading, writing, and modification of documents.

// 启动MATLAB并运行runTest()函数
            MLApp.MLApp matlab = null;
            Type matlabAppType = System.Type.GetTypeFromProgID("Matlab.Desktop.Application");
            matlab = System.Activator.CreateInstance(matlabAppType) as MLApp.MLApp;
            string path_project = Directory.GetCurrentDirectory();   //工程文件的路径,如bin下面的debug
            string path_matlab = "cd('" + path_project + "')";     //自定义matlab工作路径    这里我注释调用 
            matlab.Execute(path_matlab);
            matlab.Execute("clear all");
            matlab.Execute("close all");
            string command;
            command = @"runTest()";
            matlab.Execute(command);

(Note that runTest is a custom function and is placed in the debug folder of the project so that MATLAB can find the file.)
You can replace runTest with any MATLAB command statement, such as a = 1, so that you will get it in the MATLAB variable space Variable a, its size is 1. For
details about the COM interface, please refer to the MATLAB help document: MATLAB COM Automation Server Interface (you can find the help by searching for this phrase in the help of MATLAB). In addition, it can also control the version and startup method of MATLAB. Startup type, etc. (See the help file). A configuration often used here is: start the command window or the entire MATLAB, that is, the string parameter passed in by controlling the GetTypeFromProgID method corresponds to the following two options:

  1. Matlab.Application: Open the MATLAB command window
  2. Matlab.Desktop.Application: Open the entire desktop application MATLAB window

A passage from the MATLAB C# Book, which summarizes the main ways of interaction between C# and MATLAB:

  1. C# functions call MATLAB built-in functions in the mathematical library created from MATLAB M-files to solve the mathematical problems.
  2. C# functions call the MATLAB Workspace to perform particular tasks then transfer results from the MATLAB Workspace to C# functions
  3. C# functions use COM that is created from MATLAB M-files by using MATLAB COM Builder.

4 XML passing parameters

Because simulation requires a lot of user configuration parameters and simulation configuration parameters, for C# and MATLAB for user configuration, you cannot rely on the COM provided by MATLAB to fetch or read parameters, but need to use XML files to transfer parameters. eXtensible Markup Language, Extensible Markup Language, is a markup language. Generally, XML is used for information recording and transmission. Different languages ​​have unified parsing functions for XML files, which can be used for information interaction between different platforms or different languages. XML is often used as a configuration file.
We can rewrite the original XML file through the C# program. Then control MATLAB to parse the XML file to achieve the purpose of passing parameters. The following figure shows the display of XML files. It can be seen that XML is structured through nodes and sub-nodes. ,
XML concept: Extensible Markup Language (English: Extensible Markup Language, referred to as: XML), is a markup language. Marking refers to information symbols that computers can understand. Through this kind of marking, computers can process articles containing various information. How to define these tags, you can choose an internationally-used markup language, such as HTML, or you can use a markup language that is freely determined by relevant parties like XML. This is the scalability of the language. XML is simplified and modified from the Standard Generalized Markup Language (SGML). It mainly includes the following parts:
1, document declaration
2, element=tag
3, attribute
4, comment
5, CDATA area, special characters <! [CDATA[What I don’t want to parse]]>
Features and Convenience: Data transfer between different languages ​​C# and Java, different platforms win and linux
Markup language, not a programming language

Insert picture description here

As shown in the figure above, XML saves different parameters and configurations according to the nodes and the information attributes contained in the nodes. When the save is complete, both C# and MATLAB need the function of reading and writing XML files. In order to complete the information interaction process between C# and MATLAB. As shown below.
Insert picture description here

5 Small examples of interactive experiments

According to the above-mentioned COM-based control mode and XML file-based information interaction mode, two numerical parameters are input in the desktop application, and the MATLAB program is called to complete the relevant calculations.

C# software interaction schematic
The software interface is as shown in the figure above. The user enters the parameters and then generates an XML file through the input button. Clicking MATLAB executes will control MATLAB to read the file and read the information, and then automatically call different functions according to the information to realize the function, and finally save the calculation result As an XML file. When the user clicks to retrieve, the program reads the XML file generated by MATLAB and displays the returned result.
Insert picture description here
Software running process The
specific running process is shown in the figure above, which is mainly completed by the user operating the user interface.
1. Enter two parameters in the parameter 1 and parameter 2 dialog boxes, and then select the corresponding calculation method in the function selection drop-down box, there are two function options add and mul;
2. Generate an XML input file by clicking the MATLAB input button, and then Click the MATLAB execute button to automatically control MATLAB to execute the written function
3. The function reads the XML file and parses the user's input, then obtains the result of the operation, and writes it into the XML result file
4. C# reads the XML result file and displays it
The following figure respectively shows the XML file passed by C# to MATLAB and the result XML file saved by MATLAB.
Insert picture description here

C# XML file passed to MATLAB

Insert picture description here

The XML file passed by MATLAB to C#

The m file used by MATLAB is as follows:
mulTest.m: used to complete the multiplication function, the input is two parameters, the input result
Xmlread, m: used to complete the reading operation of the XML file
Xmlwrite.m: used to complete the XML File write operation
runTest.m: C# calls the main function run by MATLAB, parses the user input according to the data rules formulated by XML, and calculates according to the input, and writes the result into the XML file according to the data rules.
Note that all functions need to be placed in the vs project Under the debug folder, MATLAB can find these files. The
C# program reads user parameter input, uses COM to control MATLAB operation, write XML function, read XML function and control text box display.

6 Small example source code address

The xml read and write xml functions of MATLAB used here are not official, but an older brother further encapsulated them on the official basis, making it very simple and convenient to use. Download the toolkit for reading and writing xml as follows:
XML read and write interactive tool download address The
source program package download address is as follows:
small example source program download

7 Recommended learning resources

C# and MATLAB interaction

Two English books, the first is mainly to introduce the small case of C# writing application combined with embedded hardware development, the second is specifically for the interaction between C# and MATLAB, I feel that it is better to directly look at the help document of MATLAB, but the help document is for The interaction between C# and MATLAB is implemented based on COM, so what is introduced in the document is not particularly detailed.

  1. Integrating C# .Net with Embedded System
  2. MATLAB C# Book

XML learning

To learn the grammar and structure of XML, you can go to bilibili or learn the website, and then learn C# to control XML reading, writing, and other operations, and at the same time learning the operation of MATLAB on XML reading and writing.

Contact the author QQ 2807073834, email: [email protected], refuse to reach out to the party

Guess you like

Origin blog.csdn.net/qq_36320710/article/details/107114811