MathWorks.MATLAB.Engine.MATLABEngine - .NET class using MATLAB as a computational engine - MATLAB (original) (raw)

.NET class using MATLAB as a computational engine

Since R2022b

Description

The MATLABEngine class uses a MATLABĀ® process as a computational engine for .NET applications. You can call MATLAB functions as methods of a MATLABEngine object because the functions are dynamically invoked when you call them. You also can call functions and scripts that you define. You can send data to and retrieve data from the MATLAB workspace associated with the MATLABEngine object.

Use the MATLABEngine class to start a new MATLAB session or to connect to an existing one.

For information about exceptions, see MathWorks.MATLAB.Exceptions Exception Classes for .NET.

Class Details

Namespace: MathWorks.MATLAB.Engine
Superclass: System.Dynamic.DynamicObject
Interface: System.IDisposable

Unsupported Startup Options

The engine does not support these MATLAB startup options:

For information on MATLAB startup options, see Commonly Used Startup Options.

Method Summary

Static Methods

Member Variable

Workspace Access to MATLAB base workspace. Access to the global workspace is not supported.

Specialized Operators and Functions

You can call any MATLAB function as a method of a MATLABEngine object when assigned to a variable of type dynamic. The engine dynamically invokes a MATLAB function when you call it. For details, see Call MATLAB Functions.

Method Details

StartMATLAB

static MATLABEngine StartMATLAB();

static MATLABEngine StartMATLAB(string option);

static MATLABEngine StartMATLAB(string option1, ..., string optionN);

static MATLABEngine StartMATLAB(string[] options);

Description

Start MATLAB synchronously in a separate process with optional MATLAB startup options and connect to it.

Returns

Instance of MATLABEngine connected to a shared MATLAB session

Throws

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException MATLAB fails to start.
System.ArgumentNullException Null string is not a valid argument.

C# Example

Start a new MATLAB process with one startup option. For a complete code example, seeStart MATLAB with the -nodesktop Option.

using (dynamic eng = MATLABEngine.StartMATLAB("-nodesktop")) { eng.disp(new RunOptions(nargout: 0), "MATLAB started."); }

VB.NET Example

Start a new MATLAB process with default options.

Option Strict Off Using matlab As Object = MATLABEngine.StartMATLAB() matlab.disp(New RunOptions(nargout:=0), "Hello, world.") End Using

StartMATLABAsync

static Task<MATLABEngine> StartMATLABAsync();

static Task<MATLABEngine> StartMATLABAsync(string option);

static Task<MATLABEngine> StartMATLABAsync(string option1, ..., string optionN);

static Task<MATLABEngine> StartMATLABAsync(string[] options, System.Threading.CancellationToken token);

Description

Start MATLAB asynchronously in a separate process with optional MATLAB startup options and connect to it.

Parameters

string option string[] options Startup options used to start the MATLAB engine. You can specify multiple startup options. The engine supports all MATLAB startup options except the options listed in Unsupported Startup Options. For a list of options, see the platform-specific command matlab (Windows), matlab (macOS), or matlab (Linux).
CancellationToken token Cancellation token used to cancel asynchronous tasks. The default isSystem.Threading.CancellationToken.None.

Returns

Task that completes when the MATLABEngine object is instantiated and connected to MATLAB, a cancellation request is received, or an exception occurs

Throws

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException MATLAB fails to start.
System.OperationCanceledException Cancellation request received from aSystem.Threading.CancellationToken.
System.ArgumentNullException Null string is not a valid argument.

C# Example

Start two MATLAB sessions in the background, then wait for both to start before continuing. For a complete code example, see Asynchronously Start Two MATLAB Sessions.

try { Task startMatlab1 = MATLABEngine.StartMATLABAsync(); Task startMatlab2 = MATLABEngine.StartMATLABAsync();

Console.WriteLine("Two MATLAB sessions are starting in the background.");
Console.WriteLine("Wait for both to start before continuing.");
await Task.WhenAll(startMatlab1, startMatlab2);
Console.WriteLine("Two MATLAB sessions started.");

} catch (MATLABNotAvailableException) { Console.WriteLine("Could not start or connect to MATLAB engine."); }

Start MATLAB asynchronously but cancel if the operation takes more than 10 seconds.

// Create a cancel token source, and set it to cancel after 10 seconds CancellationTokenSource src = new CancellationTokenSource(); src.CancelAfter(TimeSpan.FromSeconds(10)); try { // Wait for the task to complete dynamic matlab = await MATLABEngine.StartMATLABAsync(src.Token); Console.WriteLine("MATLAB has started.");

} catch (MATLABNotAvailableException) { // Could not connect to MATLAB Console.Error.WriteLine("Could not start or connect to MATLAB engine."); } catch (OperationCanceledException) { // Task was canceled before MATLAB started Console.Error.WriteLine("Task was canceled before completion."); } finally { src.Dispose(); }

ConnectMATLAB

static MATLABEngine ConnectMATLAB();

static MATLABEngine ConnectMATLAB(string name);

Description

Connect synchronously to a shared MATLAB session on the local machine or start a new session if none exists.

Parameters

string name Name of the shared MATLAB session. Use FindMATLAB to get the names of shared MATLAB sessions.

Returns

Instance of MATLABEngine

Throws

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException MATLAB fails to start or connect.
System.ArgumentNullException Null string is not a valid argument.

C# Example

Connect to the first shared MATLAB session found or start a new one.

using (dynamic matlab = MATLABEngine.ConnectMATLAB()) { matlab.disp(new RunOptions(nargout: 0), "Hello, shared MATLAB."); }

Connect to a shared MATLAB session by name.

using (dynamic matlab = MATLABEngine.ConnectMATLAB("MATLAB_1234")) { matlab.disp(new RunOptions(nargout: 0), "Hello, MATLAB_1234.");

For an example that displays a message if unable to locate or connect toMATLAB_1234, see MathWorks.MATLAB.Exceptions.MATLABNotAvailableException.

VB.NET Example

Connect to the first shared MATLAB session found or start a new one.

Using matlab As Object = MATLABEngine.ConnectMATLAB() matlab.disp(New RunOptions(nargout: 0), "Hello, shared MATLAB.") End Using

Connect to a shared MATLAB session by name.

Option Strict Off Using matlab As Object = MATLABEngine.ConnectMATLAB("MATLAB_1234") matlab.disp(New RunOptions(nargout:=0), "Hello, "MATLAB_1234.") End Using

For an example that displays a message if unable to locate or connect toMATLAB_1234, see MathWorks.MATLAB.Exceptions.MATLABNotAvailableException.

ConnectMATLABAsync

static Task<MATLABEngine> ConnectMATLABAsync();

static Task<MATLABEngine> ConnectMATLABAsync(string name);

static Task<MATLABEngine> ConnectMATLABAsync(System.Threading.CancellationToken token);

static Task<MATLABEngine> ConnectMATLABAsync(string name, System.Threading.CancellationToken token);

Description

Connect asynchronously to a shared MATLAB session on the local machine or start a new session if none exists.

Parameters

string name Name of the shared MATLAB session. Use FindMATLABAsync to get the names of shared MATLAB sessions.
CancellationToken token Cancellation token used to cancel asynchronous tasks. The default isSystem.Threading.CancellationToken.None.

Returns

Task that completes when the MATLABEngine object is instantiated and connected to MATLAB, a cancellation request is received, or an exception occurs

Throws

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException MATLAB fails to start or connect.
System.OperationCanceledException Cancellation request received from aSystem.Threading.CancellationToken.
System.ArgumentNullException Null string is not a valid argument.

FindMATLAB

static string[] FindMATLAB();

Description

Find all shared MATLAB sessions on the local machine synchronously.

Returns

Array of the names of all shared MATLAB sessions on the local machine, or an empty array if none are available

C# Example

Connect to a specific MATLAB session.

// Find shared MATLAB sessions string[] names = MATLABEngine.FindMATLAB(); if (names.Length == 0) Console.Error.WriteLine("No shared MATLAB sessions found."); string myMATLAB = names[0]; // Pick the first using (dynamic matlab = MATLABEngine.ConnectMATLAB(myMATLAB)) { matlab.disp(new RunOptions(nargout: 0), "Hello, shared MATLAB.");

VB.NET Example

Connect to a specific MATLAB session.

Option Strict Off 'Find shared MATLAB sessions Dim names As String() = MATLABEngine.FindMATLAB() If names.Length = 0 Then Console.Error.WriteLine("No shared MATLAB sessions found.") End If Dim myMATLAB = names(0) 'Pick the first Using matlab As Object = MATLABEngine.ConnectMATLAB(myMATLAB) matlab.disp(New RunOptions(nargout:=0), "Hello, shared MATLAB.") End Using

FindMATLABAsync

static Task<string[]> FindMATLABAsync();

static Task<string[]> FindMATLABAsync(System.Threading.CancellationToken token);

Description

Find and return asynchronously the names of all shared MATLAB sessions on the local machine.

Parameters

CancellationToken token Cancellation token used to cancel asynchronous tasks. The default isSystem.Threading.CancellationToken.None.

Returns

Task that completes with an array of the names of all shared MATLAB sessions on the local machine

Throws

System.OperationCanceledException Cancellation request received from aSystem.Threading.CancellationToken.

C# Example

Connect to the first shared MATLAB session found.

static async void Main(string[] args) { string[] names = await MATLABEngine.FindMATLABAsync(); if (names.Length == 0) Console.WriteLine("No MATLAB sessions available."); else { dynamic matlab = await MATLABEngine.ConnectMATLABAsync(names[0]); matlab.disp(new RunOptions(nargout: 0), "Hello, shared MATLAB."); } }

Dispose

static void Dispose();

Description

Implicitly called to free resources created by the using statement.

C# Example

// Wrap in a using block to ensure proper disposal of unmanaged resources. using (dynamic eng = MATLABEngine.StartMATLAB()) { eng.disp(new RunOptions(nargout: 0), "Hello, world."); } // MATLABEngine.Dispose() is implicitly called when "eng" goes out of scope.

VB.NET Example

Option Strict Off 'Wrap in a using block to ensure proper disposal of unmanaged resources. Using eng As Object = MATLABEngine.StartMATLAB() eng.disp(New RunOptions(nargout:=0), "Hello, world.") End Using 'MATLABEngine.Dispose() is implicitly called when "eng" goes out of scope.

TerminateEngineClient

static void TerminateEngineClient();

Description

Release all MATLAB resources at run time.

C# Example

using (dynamic matlab = MATLABEngine.StartMATLAB()) { matlab.disp(new RunOptions(nargout: 0), "Hello, world."); } MATLABEngine.TerminateEngineClient();

VB.NET Example

Option Strict Off Using matlab As Object = MATLABEngine.StartMATLAB() matlab.disp(New RunOptions(nargout:=0), "Hello, world.") End Using MATLABEngine.TerminateEngineClient();

Call MATLAB Functions

ret = MATLABEngine.matlabfunc(dynamic arg1, ..., dynamic argN);

ret = MATLABEngine.matlabfunc(RunOptions options, __);

ret = MATLABEngine.matlabfunc(__, Name: Value);

ret = MATLABEngine.matlabfunc(__, "Name", Value);

Description

Call MATLAB function matlabfunc.

Parameters

dynamic arg1, ..., dynamic argN Arguments for the MATLAB function with default execution options. Use thedynamic type to resolve the type of the required, positional, named, and optional parameters at run time. The MATLAB function determines the type for arg1, ..., argN.
RunOptions options Execution options for the function, specified as a MathWorks.MATLAB.Types.RunOptions object. Specify the execution options before the function arguments.
Name and Value Pairs of arguments, specified in one of these formats: Name: Value"Name", Valuewhere Name is the argument name andValue is the corresponding value. Specify the name-value arguments after all the arguments in any of the previous syntaxes.

Returns

Output of the MATLAB function. For functions called synchronously, the returned value is:

For functions called asynchronously, the return value is a Task that completes when the MATLAB function completes, an exception occurs, or the task is canceled. The Task.Result property contains the output of the function.

Throws

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException Connection to MATLAB is lost.
MathWorks.MATLAB.Exceptions.MATLABExecutionException MATLAB run-time error occurred.
MathWorks.MATLAB.Exceptions.UnsupportedTypeException A parameter to the MATLAB function cannot be converted to a native MATLAB type.
System.InvalidCastException A return value from the MATLAB function cannot be cast to the given .NET type.
System.OperationCanceledException Cancellation request received from aSystem.Threading.CancellationToken.

C# Example

Call the MATLABlinspace function on engine object matlab. For a complete code example, see Pass Variables from .NET to MATLAB.

double[] A = matlab.linspace(-5.0,5.0);

Version History

Introduced in R2022b