Pergunta

I am trying to figure out a way to run a .m file from java.

When the .m file is run it outputs a text file that I need to retrieve. I already have the code to retrieve the text file in java but I still cannot figure out how to start and run the .m file from java so that it outputs the file that I need. Any ideas?

Foi útil?

Solução 4

I think MatlabControl is what you want. It's all described here: http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html

In essence, call

MatlabControl.eval("yourfile.m");

Outras dicas

You can just start a Java process and run matlab..."matlab -r "yourMfile"

Here is the code, you are looking for:

import matlabcontrol.*;

    public class matlabconnect
    {
        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.feval("matlab_file_name");

            // close connection
            proxy.disconnect();
        }

I have tested the program. It is working well. Do not forget to put your matlab file to its default path.

There is already a bit newer api for matlab / JAVA

    <dependency>
        <groupId>com.diffplug.matsim</groupId>
        <artifactId>matconsolectl</artifactId>
        <version>4.5.0</version>
    </dependency>

and

    // create proxy
    MatlabProxyFactoryOptions.Builder builder = new MatlabProxyFactoryOptions.Builder();

    MatlabProxyFactory factory = new MatlabProxyFactory(builder.build());
    // get the proxy
    MatlabProxy proxy = factory.getProxy();

    // call user-defined function (must be on the path)
    proxy.eval("addpath('"...PATH..."')");
    proxy.feval("function");

    // close connection
    proxy.disconnect();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top