Olarik Surinta
Olarik Surinta

Reputation: 119

How do I call java code from a Matlab program

I would like to calling my own Java program from Matlab.

This is my java program:

public class TestArgu{
    public static void main(String[] args){
        System.out.println("Test passing arguments!");
    }

    public void addNumber(int aNumber){
        ansNumber = aNumber+5;
        chk = aNumber;
        System.out.println("input number = " + chk + ".\n");
        System.out.println("ans = " + ansNumber + ".\n");
    }

    public int ansChk(){
        return ansNumber;
    }

    private int ansNumber;
    private int chk;
}

I did step by step from this link http://www.mathworks.nl/support/solutions/en/data/1-URS0E/?...1...

but it is not working with my program. I'm running Matlab program from the Server computer. So I cannot edit the classpath.txt.

How to fix this problem?

Upvotes: 3

Views: 3601

Answers (1)

PaxRomana99
PaxRomana99

Reputation: 574

First, delete the main function from your class. Then add the line

package mypackage.release;

before your class definition. Then compile it using the command

javac -verbose -cp /home/javaclasses -d /home/javaclasses /home/javasource/TestArgu.java

In matlab type

javaaddpath('/home/javaclasses');
clear java;
import mypackage.release.*;
test=TestArgu;
test.addNumber(6);
test.ansChk();

Remember that everytime you make changes and compile the java class, you must call clear java in matlab before the changes are available. This also has the unfortunate side effect of clearing all the variables in your workspace so make sure you don't have anything important to save before calling it.

Upvotes: 3

Related Questions