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\R2024b\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Runtime.dll

C:\Program Files\MATLAB\R2024b\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 and connects to it. If you want to launch a MATLAB Runtime instance in a separate process, set the OutOfProcessAttribute to true.

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;

// Set OutOfProcessAttribute to true
// This ensures each MATLAB Runtime instance runs in a separate process, allowing for true parallel execution
[assembly: OutOfProcess(true)]

namespace MyConsoleApp
{
    class Program
    {
        // Asynchronously calls a MATLAB function when the MATLAB Runtime instance is ready
        static async void CallDisp(Task<MATLABRuntime> matlabTask)
        {
            try
            {
                // Await the completion of the MATLAB Runtime startup
                dynamic matlab = await matlabTask;

                // Use the MATLAB instance within a using statement to ensure proper disposal
                using (matlab)
                {
                    // Call a MATLAB function with specified arguments
                    matlab.mydisp(new RunOptions(nargout: 0), "Hello, Call MATLAB!");
                }
            }
            catch (Exception ex)
            {
                // Handle any exceptions that occur during the MATLAB function call
                Console.WriteLine($"Error in MATLAB call: {ex.Message}");
                throw;
            }
        }

        static void Main(string[] args)
        {
            try
            {
                // Start two MATLAB Runtime instances asynchronously
                // Each instance will execute the CallDisp method upon startup completion
                Task workflowTask1 = MATLABRuntime.StartMATLABAsync("mydisp.ctf").ContinueWith(CallDisp);
                Task workflowTask2 = MATLABRuntime.StartMATLABAsync("mydisp.ctf").ContinueWith(CallDisp);

                // Wait for both MATLAB Runtime instances to complete their tasks
                // This ensures that the main thread does not proceed until both instances are done
                Task.WhenAll(workflowTask1, workflowTask2).Wait();
                Console.WriteLine("Done!");
            }
            catch (AggregateException ae)
            {
                // Handle exceptions that are thrown from within the tasks
                // Rethrow the inner exception for further handling or logging
                throw ae.InnerException;
            }
        }
    }
}

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

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

class Program
{
    static async Task CallMATLAB(Task<MATLABRuntime> matlabTask)
    {
        try
        {
            // Await the MATLAB Runtime task to complete and get the MATLAB instance
            using (dynamic matlab = await matlabTask)
            {
                // Call a MATLAB function using the MATLAB instance
                matlab.mydisp(new RunOptions(nargout: 0), "Hello, CallMATLAB!");
            }
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("MATLAB call was cancelled.");
            throw; // Re-throwing to be caught in the calling method
        }
    }

    static async Task Main(string[] args)
    {
        // Create a CancellationTokenSource to control task cancellation
        using (CancellationTokenSource src = new CancellationTokenSource())
        {
            // Schedule the cancellation after 10 seconds
            src.CancelAfter(TimeSpan.FromSeconds(10));

            try
            {
                // Start the MATLAB Runtime asynchronously with cancellation token
                Task workflowTask = MATLABRuntime.StartMATLABAsync("mydisp.ctf", src.Token)
                    .ContinueWith(CallMATLAB, src.Token);

                // Await the completion of the MATLAB Runtime task
                // This is a non-blocking wait and will throw an exception if cancelled
                await workflowTask;
                Console.WriteLine("Task completed successfully!");
            }
            catch (OperationCanceledException)
            {
                // Handle the cancellation of the task
                Console.Error.WriteLine("Task was cancelled before completion.");
            }
            catch (Exception ex)
            {
                // Handle any other exceptions that might occur
                Console.Error.WriteLine($"An error occurred: {ex.Message}");
                throw; // Optional: rethrow if you want to escalate the error
            }
        }
    }
}

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