javamatlabtraining-datanntool

Call a java function from matlab script


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 : enter image description here

But when I try to execute this commande from matlab

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

it tells me:

Undefined function or variable 'TestFunction'.

Solution

  • 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.