メインコンテンツ

MathWorks.MATLAB.Runtime.MATLABRuntime

MATLAB Runtime インスタンスを表す .NET クラス

R2022b 以降

説明

MATLABRuntime クラスは MATLAB® Runtime インスタンスを表します。MATLAB 関数は呼び出したときに動的に呼び出されるため、ドット表記を使用して MATLABRuntime オブジェクトのメソッドとして呼び出すことができます。

アセンブリ

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

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

クラスの詳細

名前空間:

MathWorks.MATLAB.Runtime
スーパークラス:System.Dynamic.DynamicObject
インターフェイス:System.IDisposable

メソッドの概要

静的メソッド

StartMATLAB

MATLAB Runtime インスタンスを同期的に開始

StartMATLABAsync

MATLAB Runtime インスタンスを非同期的に開始

TerminateApplication

MATLAB アプリケーションを終了

SetupMacRunLoopAndRun

macOS で実行するアプリケーション用に Core Foundation CFRunLoop を設定します。

インスタンス メソッド

WaitForFiguresToClose

アセンブリのすべての Figure が閉じるまで一時停止

Dispose

MATLAB Runtime インスタンスを明示的に終了

メソッドの詳細

StartMATLAB

static MATLABRuntime StartMATLAB(string ctfArchiveName);

説明

MATLAB Runtime インスタンスを同期的に開始し、それに接続します。MATLAB Runtime インスタンスを別のプロセスで起動する場合は、OutOfProcessAttributetrue に設定します。

パラメーター

string ctfArchiveName

デプロイ可能なアーカイブ (.ctf ファイル) の名前。

戻り値

MATLABRuntime のインスタンス。

スロー

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException

MATLAB を起動できません。

System.ArgumentNullExceptionNull 文字列は有効な引数でありません。
C# の例

新しい MATLAB Runtime インスタンスをデプロイ可能なアーカイブ (.ctf ファイル) で起動します。

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);

説明

MATLAB Runtime インスタンスを別のプロセスで非同期的に起動し、それに接続します。

パラメーター

string ctfArchiveName

デプロイ可能なアーカイブ (.ctf ファイル) の名前。

CancellationToken token

非同期タスクのキャンセルに使用するキャンセル トークン。既定では System.Threading.CancellationToken.None です。

戻り値

MATLABRuntime インスタンスがインスタンス化されるか例外が発生した時点で完了するタスク。

スロー

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException

MATLAB を起動できません。

System.ArgumentNullExceptionNull 文字列は有効な引数でありません。
C# の例

2 つの MATLAB Runtime インスタンスを非同期的に起動します。

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;
            }
        }
    }
}

MATLAB Runtime インスタンスを非同期的に開始しますが、10 秒を超えると操作をキャンセルします。

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();

説明

MATLAB アプリケーションを終了し、MATLAB Runtime インスタンスを破棄します。

C# の例
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);

説明

macOS で実行するアプリケーション用に Core Foundation CFRunLoop を設定します。このメソッドは、Nojvm 属性または OutOfProcess 属性が指定されていない場合に使用します。

パラメーター

Func<Object, int> userFunc

Object をパラメーター、int を出力として、MATLAB コードを実行するユーザー指定の関数またはメソッド。

Object args

ユーザー指定の関数またはメソッドに渡される引数。

C# の例
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();

説明

MATLAB Runtime インスタンスから作成されたすべての表示可能な Figure が閉じるまで処理を待機します。

C# の例
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();

説明

MATLAB Runtime インスタンスを明示的に終了します。これが呼び出されない場合、MATLAB Runtime インスタンスはTerminateApplicationメソッドで終了されます。

スロー

MathWorks.MATLAB.Exceptions.MATLABExecutionException

MATLAB を終了できません。

C# の例
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();
        }
    }
}

バージョン履歴

R2022b で導入