Ahmed Gad
Ahmed Gad

Reputation: 83

MATLAB:How to use java code in MATLAB?

I want to to run java code in Matlab so I can make use of what I have learned in java to enhance my MATLAB codes.

Upvotes: 1

Views: 463

Answers (1)

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

Totally quoting from here

Suppose your Java program is like this:

public class MyClass {
    public static void main( String args[] ){}
}

To call this program in MATLAB:

  1. Outside of MATLAB: Compile this class, so you have file MyClass.class

  2. Locate the classpath.txt file for the MATLAB installation. The location of this file can be found by typing the following command in MATLAB command window:

    which classpath.txt

  3. Open the 'classpath.txt' with a text editor as Administrator. Add the full path for the directory with the MyClass.class to the end of the 'classpath.txt' file as a single line and save the file.

  4. Restart MATLAB.

  5. In MATLAB: to create an object of class MyClass, type:

    o = MyClass

  6. In MATLAB: to execute main() of object o, type:

    javaMethod('main', o, '')

Alternately one may also add the directory in which the class files are to the dynamic path. Use the JAVAADDPATH command to add the directory (which contains the MyClass.class file) to JAVA's dynamic classpath. This also obviates the need to restart MATLAB. Once this is done the code can be invoked as follows:

o = MyClass;
javaMethod('main', o);

For a detailed tutorial please see this.

Upvotes: 3

Related Questions