主要内容

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

在组件类中分配多个 MATLAB 函数

R2026b

此示例向您说明如何使用多个 MATLAB® 函数创建 .NET 矩阵数学程序。

在此示例中,您执行以下步骤:

  • 将多个 MATLAB 函数分配给一个组件类。

  • 通过实例化 MatrixMathApp.cs 并使用 MatrixMathApp.vb 类库处理数据转换,在 C# 应用程序 (Factor) 或 Visual Basic® 应用程序 (MWArray) 中访问该组件。

  • 使用 Visual Studio® .NET 开发环境构建并运行 MatrixMathApp 应用程序。

MatrixMathApp 应用程序

MatrixMathApp 应用程序对具有以下形式的简单三对角矩阵(有限差分矩阵)执行 Cholesky、LU 和 QR 因式分解:

A = [ 2 -1  0  0  0
     -1  2 -1  0  0
      0 -1  2 -1  0
      0  0 -1  2 -1
      0  0  0 -1  2 ]

您在命令行中提供矩阵的大小,程序会构建矩阵并执行三个因式分解。原始矩阵和结果被打印到标准输出。您可以选择使用稀疏矩阵执行计算,通过在命令行中指定字符串“sparse”作为第二个参数。

文件

MATLAB 函数cholesky.m
ludecomp.m
qrdecomp.m
MATLAB 函数位置matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\MatrixMathExample\MatrixMathComp\
C# 代码位置matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\MatrixMathExample\MatrixMathCSApp\MatrixMathApp.cs
Visual Basic 代码位置matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\MatrixMathExample\MatrixMathVBApp\MatrixMathApp.vb

过程

  1. 将 MATLAB 产品附带的以下文件夹复制到您的工作文件夹:

    matlabroot\toolbox\dotnetbuilder\Examples\VSVersion\NET\MatrixMathExample
    

    在 MATLAB 命令提示符下,导航到工作文件夹中的新 MatrixMathExample\MatrixMathComp 子文件夹。

  2. 检查 MATLAB 函数 cholesky.m、ludecomp.m 和 qrdecomp.m。

    function [L] = Cholesky(A)
        L = chol(A);
    
    function [L,U] = LUDecomp(A)
        [L,U] = lu(A);
    function [Q,R] = QRDecomp(A)
    
        [Q,R] = qr(A);

  3. 使用以下信息,使用 .NET 程序集编译器或 compiler.build.dotNETAssembly 构建 .NET 组件:

    字段值
    库名称MatrixMathComp
    类名Factor
    要编译的文件cholesky ludecomp qrdecomp

    例如,如果您使用的是 compiler.build.dotNETAssembly,请输入:

    buildResults = compiler.build.dotNETAssembly(["cholesky.m","ludecomp.m","qrdecomp.m"], ...
    'AssemblyName','MatrixMathComp', ...
    'ClassName','Factor');

    有关详细信息,请参阅生成 MWArray .NET 程序集并构建 .NET 应用程序中的说明。

  4. 确定是否使用 C# 还是 Visual Basic 来访问组件。

    • C#

      如果您使用 C#,请为访问该组件的 C# 应用程序编写源代码。

      此示例的示例应用程序位于 MatrixMathExample\MatrixMathCSApp\MatrixMathApp.cs 中。

      using System;
      
      using MathWorks.MATLAB.NET.Utility;
      using MathWorks.MATLAB.NET.Arrays;
      
      using MatrixMathComp;
      
      namespace MathWorks.Examples.MatrixMath
      {
        /// <summary>
        /// This application computes cholesky, LU, and QR factorizations of a finite 
        ///  difference matrix of order N.
        /// The order is passed into the application on the command line.   
        /// </summary>
        /// <remarks>
        /// Command Line Arguments:
        /// <newpara></newpara>
        /// args[0] - Matrix order(N)
        /// <newpara></newpara>
        /// args[1] - (optional) sparse; Use a sparse matrix
        /// </remarks>
        class MatrixMathApp
          {
            #region MAIN
      
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
              {
                bool makeSparse= true;
                int matrixOrder= 4;
      
                MWNumericArray matrix= null; // The matrix to factor
      
                MWArray argOut= null;     // Stores single factorization result
                MWArray[] argsOut= null;  // Stores multiple factorization results
      
                try
                  {
                    // If no argument specified, use defaults
                    if (0 != args.Length)
                      {
                        // Convert matrix order
                        matrixOrder= Int32.Parse(args[0]);
      
                        if (0 >= matrixOrder)
                          {
                            throw new ArgumentOutOfRangeException("matrixOrder", matrixOrder, 
                             "Must enter a positive integer for the matrix order(N)");
                          } 
      
                        makeSparse= ((1 < args.Length) && (args[1].Equals("sparse")));
                      }
      
                    // Create the test matrix.  If the second argument is "sparse", 
                    // create a sparse matrix.
      			        matrix= (makeSparse)
      				        ? MWNumericArray.MakeSparse(matrixOrder, matrixOrder, 
                           MWArrayComplexity.Real, (matrixOrder+(2*(matrixOrder-1))))
      				        : new MWNumericArray(MWArrayComplexity.Real, 
                           MWNumericType.Double, matrixOrder, matrixOrder);
      
                    // Initialize the test matrix
                    for (int rowIdx= 1; rowIdx <= matrixOrder; rowIdx++)
                      for (int colIdx= 1; colIdx <= matrixOrder; colIdx++)
                        if (rowIdx == colIdx)
                          matrix[rowIdx, colIdx]= 2.0;
                        else if ((colIdx == rowIdx+1) || (colIdx == rowIdx-1))
                          matrix[rowIdx, colIdx]= -1.0;
      
                    // Create a new factor object
                    Factor factor= new Factor();
      
                    // Print the test matrix
                    Console.WriteLine("Test Matrix:\n{0}\n", matrix);
      
                    // Compute and print the cholesky factorization using the 
                    // single output syntax
                    argOut= factor.cholesky((MWArray)matrix);
      
                    Console.WriteLine("Cholesky 
                       Factorization:\n{0}\n", argOut);
      
                    // Compute and print the LU factorization using the multiple output syntax
                    argsOut= factor.ludecomp(2, matrix);
      
                    Console.WriteLine("LU Factorization:\nL 
                      Matrix:\n{0}\nU Matrix:\n{1}\n", argsOut[0], 
                      argsOut[1]);
      
                    MWNumericArray.DisposeArray(argsOut);
      
                    // Compute and print the QR factorization 
                    argsOut= factor.qrdecomp(2, matrix);
      
                    Console.WriteLine("QR Factorization:\nQ Matrix:\n{0}\nR Matrix:\n{1}\n", 
                      argsOut[0], argsOut[1]);
      
                    Console.ReadLine();
                  }
      
                catch(Exception exception)
                  {
                    Console.WriteLine("Error: {0}", exception);
                  }
      
                finally
                  {
                    // Free native resources
                    if (null != (object)matrix) matrix.Dispose();
                    if (null != (object)argOut) argOut.Dispose();
      
                    MWNumericArray.DisposeArray(argsOut);
                  }
              }
      
            #endregion
          }
        }
      

      此语句创建 Factor 类的一个实例:

       Factor factor= new Factor();

      以下语句调用封装 MATLAB 函数的方法:

      argOut= factor.cholesky((MWArray)matrix);
      ...
      argsOut= factor.ludecomp(2, matrix);
      ...
      argsOut= factor.qrdecomp(2, matrix);
      ...
    • Visual Basic

      如果您使用 Visual Basic,请为访问该组件的 Visual Basic 应用程序编写源代码。

      此示例的示例应用程序位于 MatrixMathExample\MatrixMathVBApp\MatrixMathApp.vb 中。

      Imports System
      
      Imports MathWorks.MATLAB.NET.Utility
      Imports MathWorks.MATLAB.NET.Arrays
      
      Imports MatrixMathComp
      
      
      Namespace MathWorks.Demo.MatrixMathApp
      
          ' <summary>
          ' This application computes cholesky, LU, and QR factorizations of a 
          '  finite difference matrix of order N.
          ' The order is passed into the application on the command line.   
          ' </summary>
          ' <remarks>
          ' Command Line Arguments:
          ' <newpara></newpara>
          ' args[0] - Matrix order(N)
          ' <newpara></newpara>
          ' args[1] - (optional) sparse; Use a sparse matrix
          ' </remarks>
          Class MatrixMathDemoApp
      
      #Region " MAIN "
      
              ' <summary>
              ' The main entry point for the application.
              ' </summary>
              Shared Sub Main(ByVal args() As String)
      
                  Dim makeSparse As Boolean = True
                  Dim matrixOrder As Integer = 4
      
                  Dim matrix As MWNumericArray = Nothing ' The matrix to factor
      
                  Dim argOut As MWArray = Nothing   ' Stores single factorization result
                  Dim argsOut() As MWArray = Nothing  ' Stores multiple factorization results
      
                  Try
                      ' If no argument specified, use defaults
                      If (0 <> args.Length) Then
                          'Convert matrix order
                          matrixOrder = Int32.Parse(args(0))
      
                          If (0 > matrixOrder) Then
                              Throw New ArgumentOutOfRangeException("matrixOrder", matrixOrder, _
                               "Must enter a positive integer for the matrix order(N)")
                          End If
      
                          makeSparse = ((1 < args.Length) AndAlso (args(1).Equals("sparse")))
                      End If
      
                      ' Create the test matrix.  If the second argument 
                      '   is "sparse", create a sparse matrix.
                      matrix = IIf(makeSparse, _
                      MWNumericArray.MakeSparse(matrixOrder, matrixOrder, 
                                                  MWArrayComplexity.Real, 
                                               (matrixOrder + (2 * (matrixOrder - 1)))), _
                      New MWNumericArray(MWArrayComplexity.Real, MWNumericType.Double, 
                                                           matrixOrder, matrixOrder))
      
                      ' Initialize the test matrix
                      For rowIdx As Integer = 1 To matrixOrder
                          For colIdx As Integer = 1 To matrixOrder
                              If rowIdx = colIdx Then
                                  matrix(rowIdx, colIdx) = New MWNumericArray(2.0)
                              ElseIf colIdx = rowIdx + 1 Or colIdx = rowIdx - 1 Then
                                  matrix(rowIdx, colIdx) = New MWNumericArray(-1.0)
                              End If
                          Next colIdx
                      Next rowIdx
      
                      ' Create a new factor object
                      Dim factor As Factor = New Factor
      
                      ' Print the test matrix
                      Console.WriteLine("Test Matrix:{0}{1}{2}", Chr(10), matrix, Chr(10))
      
                      ' Compute and print the cholesky factorization using 
                      '    the single output syntax
                      argOut = factor.cholesky(matrix)
      
                      Console.WriteLine("Cholesky Factorization:{0}{1}{2}", 
                           Chr(10), argOut, Chr(10))
      
                      ' Compute and print the LU factorization using the multiple output syntax
                      argsOut = factor.ludecomp(2, matrix)
      
                      Console.WriteLine("LU Factorization:
                            {0}L Matrix:{1}{2}{3}U Matrix:{4}{5}{6}", Chr(10), Chr(10), 
                                     argsOut(0), Chr(10), Chr(10), argsOut(1), Chr(10))
      
                      MWNumericArray.DisposeArray(argsOut)
      
                      ' Compute and print the QR factorization 
                      argsOut = factor.qrdecomp(2, matrix)
      
                      Console.WriteLine("QR Factorization:
                            {0}Q Matrix:{1}{2}{3}R Matrix:{4}{5}{6}", Chr(10), Chr(10), 
                                     argsOut(0), Chr(10), Chr(10), argsOut(1), Chr(10))
      
                      Console.ReadLine()
      
                  Catch exception As Exception
      
                      Console.WriteLine("Error: {0}", exception)
      
                  Finally
      
                      ' Free native resources
                      If Not (matrix Is Nothing) Then
                          matrix.Dispose()
                      End If
                      If Not (argOut Is Nothing) Then
                          argOut.Dispose()
                      End If
      
                      MWNumericArray.DisposeArray(argsOut)
                  End Try
              End Sub
      #End Region
          End Class
      End Namespace
      

      此语句创建 Factor 类的一个实例:

      Dim factor As Factor = New Factor

      以下语句调用封装 MATLAB 函数的方法:

      argOut = factor.cholesky(matrix)
      
      argsOut = factor.ludecomp(2, matrix)
      
      argsOut = factor.qrdecomp(2, matrix)
  5. 使用 Visual Studio 打开与您的应用程序语言相对应的 .NET 工程文件。

    • C#

      如果您使用的是 C#,则 MatrixMathCSApp 文件夹包含此示例的 Visual Studio .NET 工程文件。在 Windows® 资源管理器中双击 MatrixMathCSApp.csproj 在 Visual Studio .NET 中打开该工程。您也可以通过右键点击 MatrixMathCSApp.csproj 并选择在 MATLAB 外部打开从桌面打开它。

    • Visual Basic

      如果您使用的是 Visual Basic,则 MatrixMathVBApp 文件夹包含此示例的 Visual Studio .NET 工程文件。在 Windows 资源管理器中双击 MatrixMathVBApp.vbproj 在 Visual Studio .NET 中打开该工程。您也可以通过右键点击 MatrixMathVBApp.vbproj 并选择在 MATLAB 外部打开从桌面打开它。

  6. 添加对位于生成程序集的文件夹中的程序集文件 MatrixMathComp.dll 引用。

  7. 添加对 MWArray API 的引用。

    如果您的系统上安装了 MATLABmatlabroot\toolbox\dotnetbuilder\bin\win64\<framework_version>\MWArray.dll
    如果您的系统上安装了 MATLAB Runtime<MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\<framework_version>\MWArray.dll

  8. 在 Visual Studio 中构建并运行 MatrixMathApp 应用程序。

    该程序显示以下输出:

    Test Matrix:
       (1,1)        2
       (2,1)       -1
       (1,2)       -1
       (2,2)        2
       (3,2)       -1
       (2,3)       -1
       (3,3)        2
       (4,3)       -1
       (3,4)       -1
       (4,4)        2
    
    Cholesky Factorization:
       (1,1)       1.4142
       (1,2)      -0.7071
       (2,2)       1.2247
       (2,3)      -0.8165
       (3,3)       1.1547
       (3,4)      -0.8660
       (4,4)       1.1180
    
    LU Factorization:
    L Matrix:
       (1,1)       1.0000
       (2,1)      -0.5000
       (2,2)       1.0000
       (3,2)      -0.6667
       (3,3)       1.0000
       (4,3)      -0.7500
       (4,4)       1.0000
    U Matrix:
       (1,1)       2.0000
       (1,2)      -1.0000
       (2,2)       1.5000
       (2,3)      -1.0000
       (3,3)       1.3333
       (3,4)      -1.0000
       (4,4)       1.2500
    
    QR Factorization:
    Q Matrix:
       (1,1)      -0.8944
       (2,1)       0.4472
       (1,2)      -0.3586
       (2,2)      -0.7171
       (3,2)       0.5976
       (1,3)      -0.1952
       (2,3)      -0.3904
       (3,3)      -0.5855
       (4,3)       0.6831
       (1,4)       0.1826
       (2,4)       0.3651
       (3,4)       0.5477
       (4,4)       0.7303
    R Matrix:
       (1,1)      -2.2361
       (1,2)       1.7889
       (2,2)      -1.6733
       (1,3)      -0.4472
       (2,3)       1.9124
       (3,3)      -1.4639
       (2,4)      -0.5976
       (3,4)       1.9518
       (4,4)       0.9129

理解 MatrixMath 程序

MatrixMath 程序从命令行获取一个或两个参量。第一个参量转换为测试矩阵的整数阶。如果将字符串 sparse 作为第二个参量传递,则会创建一个稀疏矩阵来包含测试数组。然后计算 Cholesky、LU 和 QR 因式分解并显示结果。

主要方法有三个部分:

  • 第一部分设置输入矩阵,创建一个新的因子对象,并调用 cholesky、ludecomp 和 qrdecomp 方法。这部分在 try 模块内执行。这样做是为了如果在执行期间发生异常,则执行相应的 catch 模块。

  • 第二部分是 catch 模块。代码将消息打印到标准输出,让用户知道发生的错误。

  • 第三部分是 finally 模块,用于在退出之前手动清理本机资源。这是可选的,因为垃圾收集器会自动为您清理资源。

另请参阅

主题