主要内容

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

将多个 MATLAB 函数分配给 Java 类

R2026a

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

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

  1. 将多个 MATLAB 函数分配给生成的类。

  2. 手动处理本机内存管理。

  3. 通过实例化 getfactor.java 并使用 Factor 类库处理数据转换,在 MATLAB 应用程序 (MWArray) 中访问 Java 函数。

  4. 构建并运行 MatrixMathDemoApp 应用程序。

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\javabuilder\Examples\MatrixMathExample\MatrixMathDemoComp\
Java 代码位置matlabroot\toolbox\javabuilder\Examples\MatrixMathExample\MatrixMathDemoJavaApp\getfactor.java

过程

  1. 将 MATLAB 附带的 MatrixMathExample 文件夹复制到您的工作文件夹:

    copyfile(fullfile(matlabroot,'toolbox','javabuilder','Examples','MatrixMathExample'),'MatrixMathExample')

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

  2. 如果您还没有这样做,请设置您的 Java 开发环境。有关详细信息,请参阅配置用于生成 Java 包的环境。

  3. 检查 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);

  4. 使用以下信息构建 Java 包,可通过 Java 包编译器应用或 compiler.build.javaPackage 进行操作:

    字段值
    Java 包名称factormatrix
    类名factor
    要编译的文件cholesky ludecomp qrdecomp

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

    buildResults = compiler.build.javaPackage(["cholesky.m","ludecomp.m","qrdecomp.m"], ...
    'PackageName','factormatrix', ...
    'ClassName','factor');

    有关详细信息,请参阅生成 Java 包并编译 Java 应用程序中的说明。

  5. 为访问 MATLAB 函数的应用程序编写源代码。

    此示例的示例应用程序位于 MatrixMathExample\MatrixMathDemoJavaApp\getfactor.java 中。

    /* Necessary package imports */
    import com.mathworks.toolbox.javabuilder.*;
    import factormatrix.*;
    
    /*
     * getfactor class computes cholesky, LU, and QR 
     * factorizations of a finite difference matrix
     * of order N. The value of N is passed on the
     * command line. If a second command line arg
     * is passed with the value of "sparse", then
     * a sparse matrix is used.
     */
    class getfactor
    {
       public static void main(String[] args)
       {
          MWNumericArray a = null;   /* Stores matrix to factor */
          Object[] result = null;    /* Stores the result */
          factor theFactor = null;   /* Stores factor class instance */
    
          try
          {
             /* If no input, exit */
             if (args.length == 0)
             {
                System.out.println("Error: must input a positive integer");
                return;
             }
    
             /* Convert input value */
             int n = Integer.valueOf(args[0]).intValue();
    
             if (n <= 0)
             {
                System.out.println("Error: must input a positive integer");
                return;
             }
    
             /*
              * Allocate matrix. If second input is "sparse"
              * allocate a sparse array 
              */
             int[] dims = {n, n};
    
             if (args.length > 1 && args[1].equals("sparse"))
                a = MWNumericArray.newSparse(dims[0], dims[1],n+2*(n-1), 
                                      MWClassID.DOUBLE, MWComplexity.REAL);
             else
                a = MWNumericArray.newInstance(dims,MWClassID.DOUBLE, MWComplexity.REAL);
    
             /* Set matrix values */
             int[] index = {1, 1};
    
             for (index[0] = 1; index[0] <= dims[0]; index[0]++)
             {
                for (index[1] = 1; index[1] <= dims[1]; index[1]++)
                {
                   if (index[1] == index[0])
                      a.set(index, 2.0);
                   else if (index[1] == index[0]+1 || index[1] == index[0]-1)
                      a.set(index, -1.0);
                }
             }
    
             /* Create new factor object */
             theFactor = new factor();
    
             /* Print original matrix */
             System.out.println("Original matrix:");
             System.out.println(a);
    
             /* Compute cholesky factorization and print results. */
             result = theFactor.cholesky(1, a);
             System.out.println("Cholesky factorization:");
             System.out.println(result[0]);
             MWArray.disposeArray(result);
    
             /* Compute LU factorization and print results. */
             result = theFactor.ludecomp(2, a);
             System.out.println("LU factorization:");
             System.out.println("L matrix:");
             System.out.println(result[0]);
             System.out.println("U matrix:");
             System.out.println(result[1]);
             MWArray.disposeArray(result);
    
             /* Compute QR factorization and print results. */
             result = theFactor.qrdecomp(2, a);
             System.out.println("QR factorization:");
             System.out.println("Q matrix:");
             System.out.println(result[0]);
             System.out.println("R matrix:");
             System.out.println(result[1]);
          }
    
          catch (Exception e)
          {
             System.out.println("Exception: " + e.toString());
          }
    
          finally
          {
             /* Free native resources */
             MWArray.disposeArray(a);
             MWArray.disposeArray(result);
             if (theFactor != null)
                theFactor.dispose();
          }
       }
    }

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

    theFactor = new factor();
    

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

    result = theFactor.cholesky(1, a);
    ...
    result = theFactor.ludecomp(2, a);
    ...
    result = theFactor.qrdecomp(2, a);
    ...
  6. 在 MATLAB 中,导航到 MatrixMathDemoJavaApp 文件夹。

  7. 将生成的 factormatrix.jar 包复制到此文件夹中。

    例如,如果您使用了 compiler.build.javaPackage,请输入:

    copyfile(fullfile('..','MatrixMathDemoComp','factormatrixjavaPackage','factormatrix.jar'))
  8. 在命令提示符窗口中,cd 到 MatrixMathDemoJavaApp 文件夹。

  9. 使用 getfactor 编译 javac 应用程序。

    • 在 Windows® 上,键入:

      javac -classpath "matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\factormatrix.jar getfactor.java
    • 在 UNIX® 上,键入:

      javac -classpath "matlabroot/toolbox/javabuilder/jar/javabuilder.jar":./factormatrix.jar getfactor.java

    将 matlabroot 替换为 MATLAB 或 MATLAB Runtime 安装文件夹的路径。例如,对于 Linux®,路径可能是 /usr/local/MATLAB/R2026a。

  10. 使用非稀疏矩阵运行 getfactor 应用程序。

    • 在 Windows 上,键入:

      java -classpath .;"matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\factormatrix.jar getfactor 4
    • 在 UNIX 上,键入:

      java -classpath .:"matlabroot/toolbox/javabuilder/jar/javabuilder.jar":./factormatrix.jar getfactor 4

    注意

    如果您在 Mac 64 位平台上运行该应用程序,则必须在 Java 命令中添加 -d64 标志。

Original matrix:
     2    -1     0     0
    -1     2    -1     0
     0    -1     2    -1
     0     0    -1     2
Cholesky factorization:
    1.4142   -0.7071         0         0
         0    1.2247   -0.8165         0
         0         0    1.1547   -0.8660
         0         0         0    1.1180


LU factorization:
L matrix:
    1.0000         0         0         0
   -0.5000    1.0000         0         0
         0   -0.6667    1.0000         0
         0         0   -0.7500    1.0000


U matrix:
    2.0000   -1.0000         0         0
         0    1.5000   -1.0000         0
         0         0    1.3333   -1.0000
         0         0         0    1.2500


QR factorization:
Q matrix:
   -0.8944   -0.3586   -0.1952    0.1826
    0.4472   -0.7171   -0.3904    0.3651
         0    0.5976   -0.5855    0.5477
         0         0    0.6831    0.7303


R matrix:
   -2.2361    1.7889   -0.4472         0
         0   -1.6733    1.9124   -0.5976
         0         0   -1.4639    1.9518
         0         0         0    0.9129

要对稀疏矩阵运行相同的程序,请使用相同的命令并在末尾添加字符串 sparse。例如,在 Windows 上输入:

java -classpath .;"matlabroot\toolbox\javabuilder\jar\javabuilder.jar";.\factormatrix.jar getfactor 4 sparse
Original 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

理解 getfactor 程序

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

主要方法有三个部分:

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

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

  • 第三部分是 finally 模块,用于在退出之前手动清理本机资源。

另请参阅

|

主题