メインコンテンツ

.NET アプリケーションへの単純な MATLAB 関数の統合

R2026b

メモ

MATLAB® Compiler SDK™ 製品の例は matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET にあります。ここで、VSVersion は、使用している Microsoft® Visual Studio® .NET のバージョンを示します。Visual Studio で以下のソリューションを開くことにより、すべての例についてプロジェクトを読み込むことができます。

matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\DotNetExamples.sln

単純なプロットの例では、MATLAB 関数を呼び出してプロットを表示する .NET アセンブリを作成する方法について説明します。MATLAB 関数を使用して構造体配列を変更する例については、電話帳を参照してください。

以下の例では、次の手順を実行して MATLAB 関数を .NET アプリケーションに統合します。

  • MATLAB Compiler SDK 製品を使用して、MATLAB 関数を .NET クラスのメソッドに変換し、.NET アセンブリでそのクラスをラップします。

  • .NET クラスをインスタンス化し、MWArray クラス ライブラリを使用してデータ変換を処理して、C# アプリケーションまたは Visual Basic® アプリケーションでコンポーネントにアクセスします。

  • Visual Studio .NET 開発環境を使用して、生成されたアプリケーションをビルドして実行します。

前提条件

  • MATLAB Compiler SDK の .NET ターゲット要件をすべて満たしていることを確認します。詳細については、MATLAB Compiler SDK の .NET ターゲットの要件を参照してください。

  • Microsoft Visual Studio がインストールされていることを確認します。

  • アプリケーションの実行には、エンド ユーザーによる MATLAB Runtime のインストールが必要です。詳細については、MATLAB Runtime のダウンロードとインストールを参照してください。

    テスト目的で、MATLAB Runtime の代わりに MATLAB のインストールを使用することができます。

単純なプロットの作成

ファイル

MATLAB 関数の場所matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PlotExample\PlotComp\drawgraph.m
C# コードの場所matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PlotExample\PlotCSApp\PlotApp.cs
Visual Basic コードの場所matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PlotExample\PlotVBApp\PlotApp.vb

手順

  1. MATLAB 製品に付属している以下のフォルダーを作業フォルダーにコピーします。

    matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PlotExample

    MATLAB コマンド プロンプトで、作業フォルダー内の PlotExample\PlotComp サブフォルダーに移動します。

  2. PlotExample\PlotComp にある関数 drawgraph を確認します。

    function drawgraph(coords)
    plot(coords(1,:), coords(2,:));
    pause(5)
    MATLAB コマンド プロンプトでこの関数をテストします。

    x = 0:0.01:10;
    y = sin(x);
    z = [x;y];
    drawgraph(z)

    この関数により、正弦波を表示する Figure が出力されます。

  3. 次の情報を使用して、.NET アセンブリ コンパイラ アプリまたは compiler.build.dotNETAssembly で .NET コンポーネントをビルドします。

    フィールド値
    ライブラリ名PlotComp
    クラス名Plotter
    コンパイルするファイルdrawgraph.m

    たとえば、compiler.build.dotNETAssembly を使用している場合は、以下を入力します。

    buildResults = compiler.build.dotNETAssembly('drawgraph.m', ...
    'AssemblyName','PlotComp', ...
    'ClassName','Plotter');

    詳細については、MWArray .NET アセンブリの生成と .NET アプリケーションのビルドの手順を参照してください。

  4. コンポーネントにアクセスするために C# または Visual Basic のどちらを使用するのかを決定します。

    • C#

      C# を使用する場合は、コンポーネントにアクセスする C# アプリケーションのソース コードを作成します。

      この例のサンプル アプリケーションは PlotExample\PlotCSApp\PlotApp.cs にあります。

      using System;
      
      using MathWorks.MATLAB.NET.Utility;
      using MathWorks.MATLAB.NET.Arrays;
      
      using PlotComp;
      
      namespace MathWorks.Examples.PlotApp
       {
        /// <summary>
        /// This application demonstrates plotting x-y data by graphing a simple 
        /// parabola into a MATLAB figure window. 
        /// </summary>
        class PlotCSApp
          {
            #region MAIN
      
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
              {
                try
                  {
                    const int numPoints= 10;  // Number of points to plot
      
                    // Allocate native array for plot values
                    double [,] plotValues= new double[2, numPoints];
      
                    // Plot 5x vs x^2
                    for (int x= 1; x <= numPoints; x++)
                      {
                        plotValues[0, x-1]= x*5;
                        plotValues[1, x-1]= x*x;
                      }
      
                    // Create a new plotter object
                    Plotter plotter= new Plotter();
      
                    // Plot the two sets of values - Note the ability to cast 
                                    the native array to a MATLAB numeric array
                    plotter.drawgraph((MWNumericArray)plotValues);
      
                    Console.ReadLine();  // Wait for user to exit application
                  }
      
                catch(Exception exception)
                  {
                    Console.WriteLine("Error: {0}", exception);
                  }
              }
      
            #endregion
          }
        }
      
        
      
      
      

      次のステートメントは、Plotter クラスのインスタンスを作成します。

      Plotter plotter= new Plotter(); 

      次のステートメントは、ネイティブ plotValues を MWNumericArray に明示的にキャストしてから、メソッド drawgraph を呼び出します。

      plotter.drawgraph((MWNumericArray)plotValues);
      
    • Visual Basic

      Visual Basic を使用する場合は、コンポーネントにアクセスする Visual Basic アプリケーションのソース コードを作成します。

      この例のサンプル アプリケーションは PlotExample\PlotVBApp\PlotApp.vb にあります。

      Imports System
      
      Imports MathWorks.MATLAB.NET.Utility
      Imports MathWorks.MATLAB.NET.Arrays
      
      Imports PlotComp
      
      
      Namespace MathWorks.Examples.PlotApp
      
          ' <summary>
          ' This application demonstrates plotting x-y data by graphing a simple 
          ' parabola into a MATLAB figure window. 
          ' </summary>
          Class PlotDemoApp
      
      #Region " MAIN "
      
              ' <summary>
              ' The main entry point for the application.
              ' </summary>
              Shared Sub Main(ByVal args() As String)
                  Try
                      Const numPoints As Integer = 10  ' Number of points to plot
                      Dim idx As Integer
                      Dim plotValues(,) As Double = New Double(1, numPoints - 1) {}
                      Dim coords As MWNumericArray
      
                      'Plot 5x vs x^2
                      For idx = 0 To numPoints - 1
                          Dim x As Double = idx + 1
                          plotValues(0, idx) = x * 5
                          plotValues(1, idx) = x * x
                      Next idx
      
                      coords = New MWNumericArray(plotValues)
      
                      ' Create a new plotter object
                      Dim plotter As Plotter = New Plotter
      
                      ' Plot the values
                      plotter.drawgraph(coords)
      
                      Console.ReadLine()  ' Wait for user to exit application
      
                  Catch exception As Exception
                      Console.WriteLine("Error: {0}", exception)
                  End Try
              End Sub
      #End Region
          End Class
      End Namespace
      

      次のステートメントは、Plotter クラスのインスタンスを作成します。

      Dim plotter As Plotter = New Plotter

      次のステートメントは、メソッド drawgraph を呼び出します。

      plotter.drawgraph(coords)

    いずれの場合も、PlotApp プログラムにより次が実行されます。

    • double 値をもつ 2 つの配列を作成する。

    • Plotter オブジェクトを作成する。

    • drawgraph メソッドを呼び出し、MATLAB 関数 plot を使用して方程式をプロットする。

    • MWNumericArray を使用して、drawgraph メソッドで方程式をプロットするために必要なデータを表す。

    • try-catch ブロックを使用して例外をキャッチして処理する。

  5. Visual Studio を使用して、ご使用のアプリケーション言語に対応した .NET プロジェクト ファイルを開きます。

    • C#

      C# を使用する場合は、PlotCSApp フォルダーにこの例の Visual Studio .NET プロジェクト ファイルが含まれています。Windows® エクスプローラーで PlotCSApp.csproj をダブルクリックして、Visual Studio .NET でプロジェクトを開きます。[PlotCSApp.csproj] を右クリックし、[MATLAB の外部で開く] を選択して、デスクトップから開くこともできます。

    • Visual Basic

      Visual Basic を使用する場合は、PlotVBApp フォルダーにこの例の Visual Studio .NET プロジェクト ファイルが含まれています。Windows エクスプローラーで PlotVBApp.vbproj をダブルクリックして、Visual Studio .NET でプロジェクトを開きます。[PlotVBApp.vbproj] を右クリックし、[MATLAB の外部で開く] を選択して、デスクトップから開くこともできます。

  6. アセンブリを生成またはインストールしたフォルダーにあるアセンブリ ファイル PlotComp.dll への参照を追加します。

  7. MWArray API への参照を追加します。

    MATLAB がシステムにインストールされている場合matlabroot\toolbox\dotnetbuilder\bin\win64\<version>\MWArray.dll
    MATLAB Runtime がシステムにインストールされている場合<MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\<version>\MWArray.dll

  8. Visual Studio .NET で PlotApp アプリケーションをビルドして実行します。

    アプリケーションにより、次のプロットが表示されます。

    Plot of x squared.

  9. この例から発展させるには、以下のようにします。

    • 生成されたアプリケーションを別のコンピューターで実行してみる。

    • compiler.package.installer を使用してパッケージ用のインストーラーをビルドしてみる。

    • 複数の関数で構成されたアセンブリを統合してみる。

電話帳の作成

この例では、MATLAB 関数を呼び出して、電話番号が含まれた構造体配列を変更する .NET アセンブリを作成します。

ファイル

MATLAB 関数の場所matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PhoneBookExample\PhoneBookComp\makephone.m
C# コードの場所matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PhoneBookExample\PhoneBookCSApp\PhoneBookApp.cs
Visual Basic コードの場所matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PhoneBookExample\PhoneBookVBApp\PhoneBookApp.vb

手順

  1. MATLAB に付属している以下のフォルダーを作業フォルダーにコピーします。

    matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\PhoneBookExample

    MATLAB コマンド プロンプトで、作業フォルダー内の PhoneBookExample\PhoneBookComp サブフォルダーに移動します。

  2. PhoneBookExample\PhoneBookComp にある関数 makephone を確認します。

    function book = makephone(friends)
    book = friends;
    for i = 1:numel(friends)
        numberStr = num2str(book(i).phone);
        book(i).external = ['(508) 555-' numberStr];
    end

    MATLAB コマンド プロンプトでこの関数をテストします。

    friends(1).name = "Jordan Robert";
    friends(1).phone = 3386;
    friends(2).name = "Mary Smith";
    friends(2).phone = 3912;
    struct2table(makephone(friends))
    ans =
    
      2×3 table
    
             name          phone         external     
        _______________    _____    __________________
    
        "Jordan Robert"    3386     {'(508) 555-3386'}
        "Mary Smith"       3912     {'(508) 555-3912'}
    
  3. 次の情報を使用して、.NET アセンブリ コンパイラ アプリまたは compiler.build.dotNETAssembly で .NET コンポーネントをビルドします。

    フィールド値
    ライブラリ名PhoneBookComp
    クラス名PhoneBook
    コンパイルするファイルmakephone

    たとえば、compiler.build.dotNETAssembly を使用している場合は、以下を入力します。

    buildResults = compiler.build.dotNETAssembly('makephone.m', ...
    'AssemblyName','PhoneBookComp', ...
    'ClassName','PhoneBook');

    詳細については、MWArray .NET アセンブリの生成と .NET アプリケーションのビルドの手順を参照してください。

  4. コンポーネントにアクセスするために C# または Visual Basic のどちらを使用するのかを決定します。

    • C#

      C# を使用する場合は、コンポーネントにアクセスする C# アプリケーションのソース コードを作成します。

      この例のサンプル アプリケーションは
      PhoneBookExample\PhoneBookCSApp\PhoneBookApp.cs にあります。

      /* Necessary package imports */
      using System;
      using System.Collections.Generic;
      using System.Text;
      using MathWorks.MATLAB.NET.Arrays;
      using PhoneBookComp;
      
      namespace MathWorks.Examples.PhoneBookApp
      {
        //
        // This class demonstrates the use of the MWStructArray class
        //
        class PhoneBookApp
          {
            static void Main(string[] args)
              {
                PhoneBook thePhonebook = null;  /* Stores deployment class instance */
                MWStructArray friends= null;   /* Sample input data */
                MWArray[] result= null;        /* Stores the result */
                MWStructArray book= null;      /* Output data extracted from result */
      
                /* Create the new deployment object */
                thePhonebook= new PhoneBook();
      
                /* Create an MWStructArray with two fields */
                String[] myFieldNames= { "name", "phone" };
                friends= new MWStructArray(2, 2, myFieldNames);
      
                /* Populate struct with some sample data --- friends and phone */
                /*  number extensions */
                friends["name", 1]= new MWCharArray("Jordan Robert");
                friends["phone", 1]= 3386;
                friends["name", 2]= new MWCharArray("Mary Smith");
                friends["phone", 2]= 3912;
                friends["name", 3]= new MWCharArray("Stacy Flora");
                friends["phone", 3]= 3238;
                friends["name", 4]= new MWCharArray("Harry Alpert");
                friends["phone", 4]= 3077;
      
                /* Show some of the sample data */
                Console.WriteLine("Friends: ");
                Console.WriteLine(friends.ToString());
      
                /* Pass it to a MATLAB function that determines external phone number */
                result= thePhonebook.makephone(1, friends);
                book= (MWStructArray)result[0];
       
                Console.WriteLine("Result: ");
                Console.WriteLine(book.ToString());
      
                /* Extract some data from the returned structure */
                Console.WriteLine("Result record 2:");
      
                Console.WriteLine(book["name", 2]);
                Console.WriteLine(book["phone", 2]);
                Console.WriteLine(book["external", 2]);
      
                /* Print the entire result structure using the helper function below */
                Console.WriteLine("");
                Console.WriteLine("Entire structure:");
      
                DispStruct(book);
      
                Console.ReadLine();
              }
      
            public static void DispStruct(MWStructArray arr)
              {
                Console.WriteLine("Number of Elements: " + arr.NumberOfElements);
                  
                int[] dims= arr.Dimensions;
      
                Console.Write("Dimensions: " + dims[0]);
      
                for (int idx= 1; idx < dims.Length; idx++)
                  {
                    Console.WriteLine("-by-" + dims[idx]);
                  }
                  
                Console.WriteLine("\nNumber of Fields: " + arr.NumberOfFields);
                Console.WriteLine("Standard MATLAB view:");
                Console.WriteLine(arr.ToString());
      
                Console.WriteLine("Walking structure:");
      
                string[] fieldNames= arr.FieldNames;
      
                for (int element= 1; element <= arr.NumberOfElements; element++)
                  {
                    Console.WriteLine("Element " + element);
      
                    for (int field= 0; field < arr.NumberOfFields; field++)
                      {
                        MWArray fieldVal= arr[arr.FieldNames[field], element];
                          
                        /* Recursively print substructures, */
                        /*  give string display of other classes */
                        if (fieldVal.GetType() == typeof(MWStructArray))
                          {
                            Console.WriteLine("   " + fieldNames[field] + ": 
                                nested structure:");
                            Console.WriteLine("+++ Begin of \"" + fieldNames[field] + "\" 
                                nested structure");
                            DispStruct((MWStructArray)fieldVal);
                            Console.WriteLine("+++ End of \"" + fieldNames[field] + 
                                "\" nested structure");
                          }
      
                        else
                          {
                            Console.Write("   " + fieldNames[field] + ": ");
                            Console.WriteLine(fieldVal.ToString());
                          }
                      }
                  }
              }
          }
      }
      
    • Visual Basic

      Visual Basic を使用する場合は、コンポーネントにアクセスする Visual Basic アプリケーションのソース コードを作成します。

      この例のサンプル アプリケーションは
      \PhoneBookExample\PhoneBookVBApp\PhoneBookApp.vb にあります。

      ' Necessary package imports
      
      Imports MathWorks.MATLAB.NET.Arrays
      Imports PhoneBookComp
      
      '
      ' getphone class demonstrates the use of the MWStructArray class
      '
      Public Module PhoneBookVBApp
          Public Sub Main()
              Dim thePhonebook As phonebook   'Stores deployment class instance
              Dim friends As MWStructArray    'Sample input data
              Dim result As Object()          'Stores the result
              Dim book As MWStructArray       'Output data extracted from result
      
              ' Create the new deployment object 
              thePhonebook = New phonebook()
      
              ' Create an MWStructArray with two fields 
              Dim myFieldNames As String() = {"name", "phone"}
              friends = New MWStructArray(2, 2, myFieldNames)
      
              ' Populate struct with some sample data --- friends and phone numbers 
              friends("name", 1) = New MWCharArray("Jordan Robert")
              friends("phone", 1) = 3386
              friends("name", 2) = New MWCharArray("Mary Smith")
              friends("phone", 2) = 3912
              friends("name", 3) = New MWCharArray("Stacy Flora")
              friends("phone", 3) = 3238
              friends("name", 4) = New MWCharArray("Harry Alpert")
              friends("phone", 4) = 3077
      
              ' Show some of the sample data 
              Console.WriteLine("Friends: ")
              Console.WriteLine(friends.ToString())
      
              ' Pass it to a MATLAB function that determines external phone number 
              result = thePhonebook.makephone(1, friends)
              book = CType(result(0), MWStructArray)
              Console.WriteLine("Result: ")
              Console.WriteLine(book.ToString())
      
              ' Extract some data from the returned structure '
              Console.WriteLine("Result record 2:")
      
              Console.WriteLine(book("name", 2))
              Console.WriteLine(book("phone", 2))
              Console.WriteLine(book("external", 2))
      
              ' Print the entire result structure using the helper function below 
              Console.WriteLine("")
              Console.WriteLine("Entire structure:")
              dispStruct(book)
          End Sub
      
      
          Sub dispStruct(ByVal arr As MWStructArray)
              Console.WriteLine("Number of Elements: " + arr.NumberOfElements.ToString())
              'int numDims = arr.NumberofDimensions
              Dim dims As Integer() = arr.Dimensions
              Console.Write("Dimensions: " + dims(0).ToString())
      
              Dim i As Integer
              For i = 1 To dims.Length
                  Console.WriteLine("-by-" + dims(i - 1).ToString())
              Next i
              Console.WriteLine("")
              Console.WriteLine("Number of Fields: " + arr.NumberOfFields.ToString())
              Console.WriteLine("Standard MATLAB view:")
              Console.WriteLine(arr.ToString())
              Console.WriteLine("Walking structure:")
      
              Dim fieldNames As String() = arr.FieldNames
      
              Dim element As Integer
              For element = 1 To arr.NumberOfElements
                  Console.WriteLine("Element " + element.ToString())
                  Dim field As Integer
                  For field = 0 To arr.NumberOfFields - 1
                      Dim fieldVal As MWArray = arr(arr.FieldNames(field), element)
                      ' Recursively print substructures, give string display of other classes 
                      If (TypeOf fieldVal Is MWStructArray) Then
                          Console.WriteLine("   " + fieldNames(field) + ": nested structure:")
                          Console.WriteLine("+++ Begin of \"" + fieldNames[field] + 
                                                            " \ " nested structure")
      
                          dispStruct(CType(fieldVal, MWStructArray))
                          Console.WriteLine("+++ End of \"" + fieldNames[field] + 
                                                            " \ " nested structure")
                      Else
                          Console.Write("   " + fieldNames(field) + ": ")
                          Console.WriteLine(fieldVal.ToString())
                      End If
                  Next field
              Next element
          End Sub
      End Module

    いずれの場合も、PhoneBookApp プログラムにより次が実行されます。

    • MWStructArray を使用して構造体配列を作成し、名前と電話番号が含まれた例の電話帳データを表す。

    • 次のように Phonebook クラスを thePhonebook オブジェクトとしてインスタンス化する。
      thePhonebook = new phonebook();

    • 次のように、MATLAB 関数 makephone を呼び出し、追加フィールドを追加することで構造体の変更コピーを作成する。
      result = thePhonebook.makephone(1, friends);

    • 結果の構造体配列を表示する。

  5. Visual Studio を使用して、ご使用のアプリケーション言語に対応した .NET プロジェクト ファイルを開きます。

    • C#

      C# を使用する場合は、PhoneBookCSApp フォルダーにこの例の Visual Studio .NET プロジェクト ファイルが含まれています。Windows エクスプローラーで PhoneBookCSApp.csproj をダブルクリックして、Visual Studio .NET でプロジェクトを開きます。[PhoneBookCSApp.csproj] を右クリックし、[MATLAB の外部で開く] を選択して、デスクトップから開くこともできます。

    • Visual Basic

      Visual Basic を使用する場合は、PhoneBookVBApp フォルダーにこの例の Visual Studio .NET プロジェクト ファイルが含まれています。Windows エクスプローラーで PhoneBookVBApp.vbproj をダブルクリックして、Visual Studio .NET でプロジェクトを開きます。[PhoneBookVBApp.vbproj] を右クリックし、[MATLAB の外部で開く] を選択して、デスクトップから開くこともできます。

  6. アセンブリを生成したフォルダーにあるアセンブリ ファイル PhoneBookComp.dll への参照を作成します。

  7. MWArray API への参照を作成します。これは以下の場所にあります。

    MATLABmatlabroot\toolbox\dotnetbuilder\bin\win64\<version>\MWArray.dll
    MATLAB Runtime<MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\<version>\MWArray.dll

  8. Visual Studio .NET で PhoneBookComp アプリケーションをビルドして実行します。

    このアプリケーションにより、次の出力が表示されます。

    Friends: 
    2x2 struct array with fields:
        name
        phone
    Result: 
    2x2 struct array with fields:
        name
        phone
        external
    Result record 2:
    Mary Smith
    3912
    (508) 555-3912
    
    Entire structure:
    Number of Elements: 4
    Dimensions: 2-by-2
    Number of Fields: 3
    Standard MATLAB view:
    2x2 struct array with fields:
        name
        phone
        external
    Walking structure:
    Element 1
       name: Jordan Robert
       phone: 3386
       external: (508) 555-3386
    Element 2
       name: Mary Smith
       phone: 3912
       external: (508) 555-3912
    Element 3
       name: Stacy Flora
       phone: 3238
       external: (508) 555-3238
    Element 4
       name: Harry Alpert
       phone: 3077
       external: (508) 555-3077

参考

トピック