简体   繁体   中英

Run matlab function in java class in absence of matlab environment

I want to use matlab function in java application. I create java package from my function by deploytool in matlab. Now, how can i use this package? Can only import the jar file created by deploytool in my java project and use its function?

After a lot of googling, I used this toturial but in the final step, i get error "could not load file".

Also i read about MatlabControl , but in this solution, we should have matlab environment in our system to java code running. But i will run my final app in systems that may not have matlab at all.

So i need a solution to run matlab function in java class even in absence of matlab environment.

Finally I solve my problem. the solution step by step is as follows:

  1. write matlab function:

    function y = makesqr(x)

    y = magic(x);

  2. Use deploytool in matlab and create java package.

3.create new java application in Eclipse and add main class. import javabuilde.jar and makesqr.jar:

  import com.mathworks.toolbox.javabuilder.MWArray;

  import com.mathworks.toolbox.javabuilder.MWClassID;

  import com.mathworks.toolbox.javabuilder.MWNumericArray;

  import makesqr.Class1;

and main.java:

public class main {

public static void main(String[] args) {

      MWNumericArray n = null;
      Object[] result = null;
      Class1 theMagic = null;

      try
      {
         n = new MWNumericArray(Double.valueOf(5),MWClassID.DOUBLE);

         theMagic = new Class1();

         result = theMagic.makesqr(1, n);
         System.out.println(result[0]);
      }
      catch (Exception e)
      {
         System.out.println("Exception: " + e.toString());
      }
      finally
      {
         MWArray.disposeArray(n);
         MWArray.disposeArray(result);
         theMagic.dispose();
      }
}

}

  1. add javabuilder.jar and makesqr.jar to java build path of your project.

  2. run it.

the Double.valueOf(3), define the input for our function and the output is as follows:

 8     1     6
 3     5     7
 4     9     2

I didn't get properly your problem. Did you already compile the jar file from Matlab code and you are trying to use that, or you are at the last step of the tutorial?

If your answer is the latest case, most probably you forgot the "." before the class path. From tutorial you linked:

You must be sure to place a dot (.) in the first position of the class path. If it not, you get a message stating that Java cannot load the class.

Also check if the matlab compiler path ("c:\\Program Files\\MATLAB\\MATLAB Compiler Runtime\\v82\\toolbox\\javabuilder\\jar\\javabuilder.jar" - in the tutorial) is correct for your system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM