Concise notes for the impatient learner

Uncategorized

Interact with MATLAB from C#

Objective

Execute commands and exchange data with MATLAB from a C# program.

Tools

Microsoft Visual Studio
Visual Studio 2015 was used for this example.

MATLAB
Version R2016b was used for this example.

Steps

1. Setup

Create a new Visual Studio project (Console, Windows Forms, or WPF all work fine).
Add a reference to the MATLAB COM server.

matlab_reference

matlab_reference2

2. Create a MATLAB object

Create a MATLAB object. To prevent the MATLAB command window from showing, set the Visible property.

MLApp.MLApp  matlab = new MLApp.MLApp();
matlab.Visible = 0;

Even if the MATLAB window is not visible, figure windows will still appear when generated.

3. Execute a command

The simplest way to interact with MATLAB is through the Execute method. The method takes a string parameter containing the command to execute, and it returns the output of the command as a string.

string output = matlab.Execute("a = 1");

The output will be the same as in the MATLAB command line

matlab_execute

Note that if you terminate the MATLAB command with a semicolon, the output is suppressed and an empty string is returned.

4. Get a variable from MATLAB

The method GetVariable retrieves the value of a variable and returns a dynamic object. The first argument is the name of the variable. The second argument identifies the workspace (“base” or “global”).

object a = matlab.GetVariable("a", "base");

You can add a watch to examine the actual return type depending on the MATLAB variable.

5. Create a variable in MATLAB

The method PutWorkspaceData allows transferring data from C# to MATLAB. The following code creates a variable b in the base workspace and it assigns it the value 2.

matlab.PutWorkspaceData("b", "base", 2);

6. Plot

You can generate a plot by executing MATLAB commands. The plot will be displayed in a separate window.

matlab.Execute("s = sin(linspace(0,10,100)); plot(a);");

matlab_plot

7. Quit MATLAB

At the end of the program, close the MATLAB instance.

matlab.Quit();

Note: if testing a program repeatedly, leaving the instance open greatly reduces start-up time, as the MATLAB instance doesn’t need to be recreated at each launch.

Useful Links

MATLAB APIs for various languages

MATLAB COM server documentation
It includes the documentation for all the methods described in this post.

Leave a Reply