Call a java function from matlab script

一笑奈何 提交于 2020-01-06 23:53:13

问题


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[])
  {

  }
}

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.

EDIT: 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

And this is the version on jdk which I used to compile my class :

But when I try to execute this commande from matlab

>> javaaddpath 'C:\scriptsMatlab'
>> obj = TestFunction

it tells me:

Undefined function or variable 'TestFunction'.

回答1:


Option 1

  1. Check if same JRE/JDK is being used to compile your JAVA file. Execute on Matlab:

    version -java
    
  2. Compie your MyFunction.java with same jdk as above , and locate your MyFunction.class

  3. Locate your Matlab classpath.txt. Type following into matlab cmd.

    which classpath.txt
    
  4. 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.

  5. Restart Matlab.

  6. To run in Matlab . Create object of MyFunction.

    obj = MyFunction
    

    To run main() method in matlab.

    javaMethod('main', obj, '')
    

Option 2

Follow Steps 1-2.

Execute following command in Matlab

JAVAADDPATH PATH/to/Directoryof MyFunction.class.

No need to restart Matlab here. Just run using

obj = MyFunction;
javaMethod('main', obj);

From MathWorks :

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) calls the static method in class ClassName.



来源:https://stackoverflow.com/questions/36989040/call-a-java-function-from-matlab-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!