Main Content

MathWorks.MATLAB.Runtime.MATLABRuntime

.NET class that represents a MATLAB Runtime instance

Since R2022b

Description

The MATLABRuntime class represents a MATLAB® Runtime instance. You can call MATLAB functions as methods of a MATLABRuntime object using dot notation because the functions are dynamically invoked when you call them.

Assemblies

C:\Program Files\MATLAB\R2023b\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Runtime.dll

C:\Program Files\MATLAB\R2023b\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Types.dll

Class Details

Namespace:

MathWorks.MATLAB.Runtime
Superclass:System.Dynamic.DynamicObject
Interface:System.IDisposable

Method Summary

Static Methods

StartMATLAB

Start MATLAB Runtime instance synchronously

StartMATLABAsync

Start MATLAB Runtime instance asynchronously

TerminateApplication

Terminate MATLAB application

SetupMacRunLoopAndRun

Set up Core Foundation CFRunLoop for an application running on macOS.

Instance Methods

WaitForFiguresToClose

Pause until all figures in an assembly have been closed

Dispose

Terminate MATLAB Runtime instance explicitly

Method Details

StartMATLAB

static MATLABRuntime StartMATLAB(string ctfArchiveName);

Description

Start MATLAB Runtime instance synchronously in a separate process and connect to it.

Parameters

string ctfArchiveName

Name of deployable archive (.ctf file).

Returns

Instance of MATLABRuntime.

Throws

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException

MATLAB fails to start.

System.ArgumentNullExceptionNull string is not a valid argument.
C# Example

Start a new MATLAB Runtime instance with a deployable archive (.ctf file).

using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\mylinspace.ctf ";
            using (dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath))
            {
                double[] vec = matlab.mylinspace(1.0, 100.0);
                foreach (double i in vec)
                {
                    Console.Write("{0} ", i);
                }
            }
            Console.ReadLine();
        }
    }
}

StartMATLABAsync

static Task<MATLABRuntime> StartMATLABAsync(string ctfArchiveName);

static Task<MATLABRuntime> StartMATLABAsync(string ctfArchiveName, System.Threading.CancellationToken token);

Description

Start a MATLAB Runtime instance asynchronously in a separate process and connect to it.

Parameters

string ctfArchiveName

Name of deployable archive (.ctf file).

CancellationToken token

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

Returns

Task that completes when the MATLABRuntime instance is instantiated or an exception occurs.

Throws

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException

MATLAB fails to start.

System.ArgumentNullExceptionNull string is not a valid argument.
C# Example

Start two MATLAB Runtime instances asynchronously.

using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

static async void CallDisp(Task<MATLABRuntime> matlabTask)
{
    dynamic matlab = await matlabTask;
    using (matlab)
    {
        matlab.mydisp(new RunOptions(nargout: 0), "Hello, Call MATLAB!");
    }
}
try
{
    // First MATLAB Runtime instance creation, specify the callback function
    Task workflowTask1 = MATLABRuntime.StartMATLABAsync("mydisp.ctf").ContinueWith(CallDisp);

    // Second MATLAB Runtime instance creation, specify the callback function
    Task workflowTask2 = MATLABRuntime.StartMATLABAsync("mydisp.ctf").ContinueWith(CallDisp);

    // Each of the above tasks is currently executing in the background
    // Wait for all of those tasks to start, execute, and terminate
    Task.WhenAll(workflowTask1, workflowTask2).Wait();
    Console.WriteLine("Done!");

// Handle exceptions thrown from within the task
} catch (AggregateException ae) {
    // Rethrow any other exceptions
    throw ae.InnerException;
}

Start a MATLAB Runtime instance asynchronously, but cancel if the operation takes more than 10 seconds.

using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

static async Task CallMATLAB(Task<MATLABRuntime> matlabTask) {
    using (dynamic matlab = await matlabTask) {
        matlab.mydisp(new RunOptions(nargout: 0), "Hello, CallMATLAB!");
    }
}
 
// Create a cancel token source, and kickoff the task
CancellationTokenSource src = new CancellationTokenSource();
Task workflowTask = MATLABRuntime
    .StartMATLABAsync("mydisp.ctf",src.Token)
    .ContinueWith(CallMATLAB);

// Cancel the above task after 10 seconds. This method is non-blocking.
src.CancelAfter(TimeSpan.FromSeconds(10));
try {
    // Wait for the task to complete
    workflowTask.Wait();
    Console.WriteLine("Task completed successfully!");
} catch (AggregateException ae) {
    if (ae.InnerException is OperationCancelledException)
        Console.Error.WriteLine("Task was cancelled before completion.");
    else // Rethrow any other exceptions
        throw ae.InnerException;
} finally {
    src.Dispose();
}

TerminateApplication

static void TerminateApplication();

Description

Terminate the MATLAB application and tear-down MATLAB Runtime instances.

C# Example
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\mylinspace.ctf ";
            dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath);
            double[] dbls = matlab.mylinspace(1.0, 100.0);
            foreach (double i in dbls)
            {
                Console.Write("{0} ", i);
            }
            Console.ReadLine();
            MATLABRuntime.TerminateApplication();
        }
    }
}

SetupMacRunLoopAndRun

static void SetupMacRunLoopAndRun(Func<Object, int> userFunc, Object args);

Description

Set up Core Foundation CFRunLoop for an application running on macOS. Use this method if Nojvm or OutOfProcess attribute is not specified.

Parameters

Func<Object, int> userFunc

User specified function or method that runs MATLAB code with Object as the parameter and int as the output.

Object args

Arguments passed to the user specified function or method.

C# Example
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;
using MathWorks.MATLAB.Exceptions;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Dynamic;
[assembly: RuntimeOption("-softwareopenglmesa")] 

namespace MyConsoleApp
{
  public class Program
  {
    static void Main(string[] args)
    {
        MATLABRuntime.SetupMacRunLoopAndRun(MainFunc, null);
    }
    static int MainFunc(Object args)
    {
      try 
      {
        string ctfPath = @"P:\MATLAB\work\matlabfunccomp.ctf ";
		using (dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath))
        {
          matlab.myFun(new RunOptions(nargout: 0), "all");
        }
      } 
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message + DateTime.Now.ToLongTimeString());
      }
      Thread.Sleep(100);
      Console.WriteLine("Terminating Application");
      MATLABRuntime.TerminateApplication();
      return 0;
    }
  }
}

WaitForFiguresToClose

void WaitForFiguresToClose();

Description

Wait for all visible figures created from the MATLAB Runtime instance to close before proceeding.

C# Example
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\myPlot.ctf ";
            using (dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath))
            {
                matlab.myPlot(new RunOptions(nargout: 0), 10.0);
                matlab.WaitForFiguresToClose();
            }
        }
    }
}

Dispose

void Dispose();

Description

Terminate MATLAB Runtime instance explicitly. If not called, the MATLAB Runtime instance will be terminated by the TerminateApplication method.

Throws

MathWorks.MATLAB.Exceptions.MATLABExecutionException

MATLAB fails to terminate.

C# Example
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\dotnetnew\output\mylinspace.ctf ";
            dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath);
            double[] vec = matlab.mylinspace(1.0, 100.0);
            foreach (double i in vec)
            {
                Console.Write("{0} ", i);
            }
            matlab.Dispose();
        }
    }
}

Version History

Introduced in R2022b