对该例子所有代码的解释 —— 请版主推荐我的文章
/* getmagic.java
* This file is used as an example for the MATLAB
* Builder for Java Language product.
*
* Copyright 2001-2006 The MathWorks, Inc.
*/
/* Necessary package imports */
import com.mathworks.toolbox.javabuilder.*;
import magicsquare.*;
/*
* getmagic class computes a magic square of order N. The
* positive integer N is passed on the command line.
*/
class getmagic{
public static void main(String[] args)
{ MWNumericArray n = null; /* Stores input value */ // 建立matlab 类库中array型 n对象,并初始化为空
Object[] result = null; /* Stores the result */ 建立结果 对象数组 result 并初始化为空
magic theMagic = null; /* Stores magic class instance */ 建立magic 类的一个实例,并初始化为一个类
try //try。。。catch
{
/* If no input, exit */
if (args.length == 0) //如果输入的数据长度为零,即n没有数据值,如命令行输入java getmagic //& 无n
{
System.out.println("Error: must input a positiveinteger");
return;
}
/* Convert and print input value*/
n = new MWNumericArray(Double.valueOf(args[0]),MWClassID.DOUBLE);将输入值args[0]), 实例化为matlab MWNumericArray类型n,
System.out.println("Magic square of order " + n.toString()); //输出n 如 2
/* Create new magic object */
theMagic = new magic();
/* Compute magic square and print result */
result = theMagic.makesqr(1, n); //这是代码的关键部分 对象theMagic的方法makesqr(1, n);有两个参数
(1,n) 其中1为 返回的变量个数 ,n 为输入值 。在matlab代码中的形式 function y = makesqr(x) y就是那个输出变量。
System.out.println(result[0]); 输出result[0】即 第一个输出变量y,若function 【y,x】 = makesqr(x)
则输出变量为 result【0】,result【1】 System.out.println(result[0]); 输出的数据为
1 3 4 2
通过下面的方法可获得每个数据的值,
MWNumericArray data_w1=null; /* Stores result[2] data;*/
float [] ss=new float[10000]; /* Stores result[2] data ;*/
data_w1=(MWNumericArray)result[0];
ss=data_w1.getFloatData();
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
/* Free native resources */
MWArray.disposeArray(n);
MWArray.disposeArray(result);
if (theMagic != null)
theMagic.dispose();
}
}
}