How to call a user defined Matlab from Java using matlabcontrol.jar

前端 未结 1 1023
[愿得一人]
[愿得一人] 2020-12-03 06:13

I am trying to call a user defined Matlab Function(M file) which takes 3 arguments(Java Strings) from my Java application which is developed in Eclipse. At the moment I am a

相关标签:
1条回答
  • 2020-12-03 06:34

    You must have any user-defined m-files on the MATLAB search path, just as if you were working normally inside MATLAB.

    I tested with the following example:

    C:\some\path\myfunc.m

    function myfunc()
        disp('hello from MYFUNC')
    end
    

    HelloWorld.java

    import matlabcontrol.*;
    
    public class HelloWorld
    {
        public static void main(String[] args)
            throws MatlabConnectionException, MatlabInvocationException
        {
             // create proxy
             MatlabProxyFactoryOptions options =
                new MatlabProxyFactoryOptions.Builder()
                    .setUsePreviouslyControlledSession(true)
                    .build();
            MatlabProxyFactory factory = new MatlabProxyFactory(options);
            MatlabProxy proxy = factory.getProxy();
    
            // call builtin function
            proxy.eval("disp('hello world')");
    
            // call user-defined function (must be on the path)
            proxy.eval("addpath('C:\\some\\path')");
            proxy.feval("myfunc");
            proxy.eval("rmpath('C:\\some\\path')");
    
            // close connection
            proxy.disconnect();
        }
    }
    

    We compile and run the Java program:

    javac -cp matlabcontrol-4.0.0.jar HelloWorld.java
    java -cp ".;matlabcontrol-4.0.0.jar" HelloWorld
    

    a MATLAB session will open up, and display the output:

    hello world
    hello from MYFUNC
    

    You could also add your folder to the path once, then persist it using SAVEPATH. That way you won't have to do it each time.

    0 讨论(0)
提交回复
热议问题