MathWorks.MATLAB.Engine.MATLABEngine
.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:
-h
-help
-?
-n
-e
-softwareopengl
-logfile
For information on MATLAB startup options, see Commonly Used Startup Options.
Method Summary
Static Methods
StartMATLAB | Start MATLAB synchronously. |
StartMATLABAsync | Start MATLAB asynchronously. |
ConnectMATLAB | Connect to shared MATLAB session synchronously. |
ConnectMATLABAsync | Connect to shared MATLAB session asynchronously. |
FindMATLAB | Find shared MATLAB sessions synchronously. |
FindMATLABAsync | Find shared MATLAB sessions asynchronously. |
Dispose | Implicitly called to free resources created by the
|
TerminateEngineClient | Release all MATLAB resources at run time. |
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);
Start MATLAB synchronously in a separate process with optional MATLAB startup options and connect to it.
| Startup options used to start the MATLAB engine. You can specify multiple startup options. The engine
supports all MATLAB startup options except for options listed in Unsupported Startup Options. For a
list of options, see the platform-specific command |
Instance of MATLABEngine
connected to a shared MATLAB session
| MATLAB fails to start. |
System.ArgumentNullException | Null string is not a valid argument. |
Start a new MATLAB process with one startup option. For a complete code example, see Start MATLAB with the -nosplash Option.
using (dynamic eng = MATLABEngine.StartMATLAB("-nosplash")) { eng.disp(new RunOptions(nargout: 0), "MATLAB started."); }
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);
Start MATLAB asynchronously in a separate process with optional MATLAB startup options and connect to it.
| 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 |
CancellationToken token | Cancellation token used to cancel asynchronous tasks. The default is
|
Task that completes when the MATLABEngine
object is instantiated and
connected to MATLAB, a cancellation request is received, or an exception occurs
| MATLAB fails to start. |
System.OperationCanceledException | Cancellation request received from a
System.Threading.CancellationToken . |
System.ArgumentNullException | Null string is not a valid argument. |
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<MATLABEngine> startMatlab1 = MATLABEngine.StartMATLABAsync(); Task<MATLABEngine> 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);
Connect synchronously to a shared MATLAB session on the local machine or start a new session if none exists.
If you specify the name of a shared MATLAB session but the engine cannot find a session with that name, then the engine throws
MathWorks.MATLAB.Exceptions.MATLABNotAvailableException
.If you do not specify a name and there are no shared MATLAB sessions available, the engine starts a new shared MATLAB session with default options.
If you do not specify a name and there are shared MATLAB sessions available, the engine connects to the first available session.
| Name of the shared MATLAB session. Use |
Instance of MATLABEngine
| MATLAB fails to start or connect. |
System.ArgumentNullException | Null string is not a valid argument. |
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 to
MATLAB_1234
, see MathWorks.MATLAB.Exceptions.MATLABNotAvailableException.
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 to
MATLAB_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);
Connect asynchronously to a shared MATLAB session on the local machine or start a new session if none exists.
If you specify the name of a shared MATLAB session but the engine cannot find a session with that name, then the engine throws
MathWorks.MATLAB.Exceptions.MATLABNotAvailableException
.If you do not specify a name and there are no shared MATLAB sessions available, the engine starts a new shared MATLAB session with default options.
If you do not specify a name and there are shared MATLAB sessions available, the engine connects to the first available session.
| Name of the shared MATLAB session. Use |
CancellationToken token | Cancellation token used to cancel asynchronous tasks. The default is
|
Task that completes when the MATLABEngine
object is instantiated and
connected to MATLAB, a cancellation request is received, or an exception occurs
| MATLAB fails to start or connect. |
System.OperationCanceledException | Cancellation request received from a
System.Threading.CancellationToken . |
System.ArgumentNullException | Null string is not a valid argument. |
FindMATLAB
static string[] FindMATLAB();
Find all shared MATLAB sessions on the local machine synchronously.
None
Array of the names of all shared MATLAB sessions on the local machine, or an empty array if none are available
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.");
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);
Find and return asynchronously the names of all shared MATLAB sessions on the local machine.
CancellationToken token | Cancellation token used to cancel asynchronous tasks. The default is
|
Task that completes with an array of the names of all shared MATLAB sessions on the local machine
System.OperationCanceledException | Cancellation request received from a
System.Threading.CancellationToken . |
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();
Implicitly called to free resources created by the using
statement.
// 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.
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();
Release all MATLAB resources at run time.
using (dynamic matlab = MATLABEngine.StartMATLAB()) { matlab.disp(new RunOptions(nargout: 0), "Hello, world."); } MATLABEngine.TerminateEngineClient();
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);
Call MATLAB function matlabfunc
.
| Arguments for the MATLAB function with default execution options. Use the
|
| Execution options for the function, specified as a |
| Pairs of arguments, specified in one of these formats:
where |
Output of the MATLAB function. For functions called synchronously, the returned value is:
null
, for MATLAB commandsOutput of the function, for functions with single outputs
ValueTuple
wrapping each output, for functions with multiple outputs
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.
| Connection to MATLAB is lost. |
| MATLAB run-time error occurred. |
| 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 a
|
Call the MATLAB
linspace
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