近期需要java调用matlab程序,花了大半天时间终于完成了一个小程序的测试,与大家分享一下成果
一、在MATLAB中编辑operation.m,
%定义一个函数operation(a,b),求a与b的加减乘除运算,并返回结果
%函数定义function 输出变量列表[s,m,...] 函数名(输入变量列表)sum,sub,mul,div中
function [sum,sub,mul,div] = operation(a,b);
sum = a + b;
sub = a - b;
mul = a * b;
div = a / b;
end
二、生成Java调用文件
Matlab命令中输入deploytool,新建一个matlab builder ja文件,在operationclass中添加operation.m文件,点击bulid the project,生成一个供java调用的文件夹结构如下:
Operation -----|----distrib
| |-----operation.jar
| |-----readme.txt
|
-------src
| |----operation
| |----operationclass.java
| |----operationMCRFactory.java
|----operationclassRemote.java
| |----classes
| |----operation
| |----operation.ctf
| |---- operationclass$1.class
|---- operationclass.class
|---- operationclassRemote.class
|---- operationMCRFactory.class
|-------build.log
|-------operation.ctf
| -------operation.jar
|-------mccExcludedFiles.log
|-------readme.txt
三、Java中建立一个java project工程JavaTestMatlab,导入两个库文件javabuilder.jar(C:\ProgramFiles
\toolbox\javabuilder\jar)和operation.jar(D:\My Documents\MATLAB\operation\distrib\ operation.jar),
编写java程序JavaTestMatlab.java程序如下:
/*java 调用matlab程序
* author:farseer
* EMail:zhf0374@126.com
* 从键盘输入两个整数,调用operation.m中的函数operation(a,b),求出两个数的各、差、积、商并输出
*/
import operation.*;
import java.util.Scanner;
class JavaTestMatlab
{
public static void main(String[] args)
{
Object result[] = null; /* object是所有类的父类public Object[] operation(int nargout, Object... rhs) */
operationclass myAdd = null; /* Stores myadd class instance */
try
{
int a,b;
myAdd = new operationclass();
System.out.println("从键盘输入两个操作数:");
System.out.print(" 输入第一个操作数:");
Scanner scan = new Scanner(System.in); //从控制台读入输入的整数
a = scan.nextInt(); //从控制台输入第一个操作数
System.out.print(" 输入第二个操作数: ");
b = scan.nextInt(); //从控制台输入第二个操作数
result = myAdd.operation(4,a,b); //operation(4,a,b)中第一个参数是返回值的个数 ,a是第一个输入参数,b是第二个输入参数
System.out.print("The sum of " + Integer.toString(a) + " and " + Integer.toString(b) + " is: ");
System.out.println(result[0]);
System.out.print("The sub of " + Integer.toString(a) + " and " + Integer.toString(b) + " is: ");
System.out.println(result[1]);
System.out.print("The mul of " + Integer.toString(a) + " and " + Integer.toString(b) + " is: ");
System.out.println(result[2]);
System.out.print("The div of " + Integer.toString(a) + " and " + Integer.toString(b) + " is: ");
System.out.println(result[3]);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
测试结果如下:
从键盘输入两个操作数:
输入第一个操作数:55
输入第二个操作数: 22
The sum of 55 and 22 is: 77
The sub of 55 and 22 is: 33
The mul of 55 and 22 is: 1210
The div of 55 and 22 is: 3
四、 错误调试
1. 安装matlab不完整,没有toolbox\javabuilder下的文件
2. 环境变量中classpath中添加两个jar文件的路径