从Matlab脚本调用Java函数 [英] Call a java function from matlab script
问题描述
我正在尝试从Matlab
脚本调用Java函数,我尝试了网站中提供的所有解决方案,但没有遇到任何问题.
我的课程很简单:
I'm trying to call a java function from a Matlab
script, I tried all the solutions put in the website but I didn't get an issue.
My class is simple:
package testMatlabInterface;
public class TestFunction
{
private double value;
public TestFunction()
{
value=0;
}
public double Add(double v)
{
value += v;
return value;
}
public static void main(String args[])
{
}
}
因此我将.java
文件(也是.class
)放在我的工作空间C:\scriptsMatlab
中,并将此路径添加到Matlab的javaclasspath
中,但是当我尝试调用该函数时,它告诉我没有类的名称在Matlab
的javaclasspath
中.
So I put .java
file (also .class
) in my workingspace C:\scriptsMatlab
and I added this path to javaclasspath
of Matlab, but when I try to call the function , it tells me that there's no class with this name in javaclasspath
of Matlab
.
这是Matlab使用的Java版本:
Here's the version of java that Matlab uses:
Java 1.6.0_17-b04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode
这是我用来编译类的jdk版本:
And this is the version on jdk which I used to compile my class :
但是当我尝试从matlab执行此命令时
But when I try to execute this commande from matlab
>> javaaddpath 'C:\scriptsMatlab'
>> obj = TestFunction
它告诉我:
Undefined function or variable 'TestFunction'.
推荐答案
选项1
-
检查是否使用相同的JRE/JDK来编译您的JAVA文件.在Matlab上执行:
Check if same JRE/JDK is being used to compile your JAVA file. Execute on Matlab:
version -java
使用上述的 jdk 来编译 MyFunction.java ,然后找到您的 MyFunction.class
Compie your MyFunction.java with same jdk as above , and locate your MyFunction.class
找到您的Matlab classpath.txt.在matlab cmd中输入以下内容.
Locate your Matlab classpath.txt. Type following into matlab cmd.
which classpath.txt
以管理员身份打开classpath.txt.在
Open your classpath.txt as administrator.Add the full path for the directory with the MyFunction.class to the end of the 'classpath.txt' file as a single line and save the file.
重新启动Matlab.
Restart Matlab.
要在Matlab中运行.创建MyFunction的对象.
To run in Matlab . Create object of MyFunction.
obj = MyFunction
要在matlab中运行main()方法.
To run main() method in matlab.
javaMethod('main', obj, '')
选项2
按照步骤1-2.
在Matlab中执行以下命令
Execute following command in Matlab
JAVAADDPATH PATH/to/Directoryof MyFunction.class
.
无需在此处重新启动Matlab. 只需使用
No need to restart Matlab here. Just run using
obj = MyFunction;
javaMethod('main', obj);
来自MathWorks:
From MathWorks :
javaMethod(MethodName,JavaObj,x1,...,xN)调用Java®对象数组的类中具有与参数x1,...,xN匹配的签名的方法.
javaMethod(MethodName,JavaObj,x1,...,xN) calls the method in the class of the Java® object array with the signature matching the arguments x1,...,xN.
javaMethod(StaticMethodName,ClassName,x1,...,xN)调用类ClassName中的静态方法.
javaMethod(StaticMethodName,ClassName,x1,...,xN) calls the static method in class ClassName.
这篇关于从Matlab脚本调用Java函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!