主要内容

本页采用了机器翻译。点击此处可查看英文原文。

将简单的 MATLAB 函数集成到 .NET 应用程序中

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 来代替 MATLAB Runtime。

创建简单绘图

文件

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. 检查位于 drawgraph 中的 PlotExample\PlotComp 函数。

    function drawgraph(coords)
    plot(coords(1,:), coords(2,:));
    pause(5)
    在 MATLAB 命令提示符下测试该函数。

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

    该函数输出一个显示正弦波的图形。

  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 程序都会执行以下操作:

    • 创建两个双精度值数组。

    • 创建一个 Plotter 对象。

    • 调用 drawgraph 方法使用 MATLABplot 函数绘制方程。

    • 使用 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 的引用。

    如果您的系统上安装了 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 中构建并运行 PlotApp 应用程序。

    应用程序显示以下绘图:

    Plot of x squared.

  9. 继续这个示例:

    • 尝试在另一台计算机上运行生成的应用程序。

    • 尝试使用 compiler.package.installer 为该包构建一个安装程序。

    • 尝试集成由多个函数组成的程序集。

创建电话簿

在此示例中,您将创建一个 .NET 程序集,该程序集调用 MATLAB 函数来修改包含电话号码的结构体数组。

文件

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. 检查位于 makephone 中的 PhoneBookExample\PhoneBookComp 函数。

    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

另请参阅

主题